Jump to content

make javascript load faster?


martinvie

Recommended Posts

Hi all,Let's say I have a lot of buttons with onclick events. It seems to me I have 4 main options to code the event handling:-------------------#1:<head> <script> function doSomething(){ doThis; doThat; doMore; } </script></head><body> <input type = "button" onClick = "doSomething()"></body>--------------------#2:<head> <script> window.onload = function(){ document.getElementById("idKnopf").onclick = doSomething; } function doSomething(){ doThis; doThat; doMore; } </script></head><body> <input type = "button" id="idKnopf"></body>--------------------#3:<head> <script> window.onload = function(){ document.getElementById("idKnopf").onclick = doSomething; function doSomething(){ doThis; doThat; doMore; } } </script></head><body> <input type = "button" id="idKnopf"></body>--------------------#4:<head> <script> window.onload = function(){ document.getElementById("idKnopf").onclick = function(){ doThis; doThat; doMore; } } </script></head><body> <input type = "button" id="idKnopf"></body>--------------------Is there a difference in Performance?Is there a difference between #2 and #3?Will the complete function be written into the object immediately in all 4 cases, like it should be expected in #4, or wil #2 or #3 just write a reference into the object and read the function only when it is called, that is when the event is triggered?Could it be that #2 or #3 will load faster, but will take slightly longer to execute the function when the body is clicked, or doesn't it make a difference at all?I am writing a rather longish HTML application and I want to reduce the loading time as much as possible.Every little hint will be appreciatedCheersMartin

Link to comment
Share on other sites

I think all codes are equivalent.Internally javascript would take same time to execute the functions in all 4 cases.One thing is that line of the code should be as small as possible.Unnessesarily putting .onclick method would cause an extra line to be parsed by the browser. That may delay the loading with a fraction of second. This is overhead because you can eliminate this by associating functions in the tags definition.element.onclick=fun() would be internally same as < onclick=fun()>I suggest it would be better to associate functions in Tags instead of defining in the window.onload function.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...