I was wondering if the window.onload = function(){} (or any other kind of onload, like the jQuery $(document).ready(); is necessary if the code is placed at the bottom of my <body>?
Or there could be highly unexpected side-effects?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, there could be unexpected consequences. But, no, it’s not absolutely necessary. The timing could be off for things still loading, like complicated layouts, deep DOM structures, dynamic HTML from other scripts, or images. To avoid these situations, it’s always safest to wrap your script in an
onloadevent.Here are some examples that demonstrate this. All examples tested on Chrome 17.0.963.12 dev on OS X. Browser results may vary when not using
onload, which demonstrates its unpredictable behavior. The examples returnfailif the result is different than what you’d expect (i.e. what your design specifies) and returnsuccesswhen the result matches what you would expect. Withonloadthey always returnsuccess.Example 1
In this example, the code is expecting the image to be a certain width. If the code is wrapped in an
onloadevent the width is correct, otherwise, it’s not.Demo: http://jsfiddle.net/ThinkingStiff/qUWxX/
HTML:
Script:
You’ll see the jsFiddle is set to “onLoad” in the upper left corner of the page and the result above the image is
success.Change that to “onDomReady” or “no wrap (body)”:
Now press “Run” at the top left of the page:
The result above the image will now be
fail.Example 2
Here is another example that doesn’t use images. In this one, an inline script has been added to the HTML. The code is expecting the width to be what it was set to by the inline script. With
onloadit’s corrent, without, it’s not. Use the same instructions as before for this demo.Demo: http://jsfiddle.net/ThinkingStiff/n7GWt/
HTML:
Script:
Example 3
Here’s an example that uses no images or Javascript in the body, just CSS. Again, the results are different between
onloadand not.Demo: http://jsfiddle.net/ThinkingStiff/HN2bH/
CSS:
HTML:
Script:
There are just too many scenarios where not wrapping your code can cause issues that you won’t be able to anticipate. To avoid these situations, it’s always safest to wrap your script in an
onloadevent.