Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the 'onload' necessary when the code is at the bottom?

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?

like image 251
ajax333221 Avatar asked Jan 03 '12 19:01

ajax333221


People also ask

Where do you put onload?

onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well (see "Supported HTML tags" below).

Why do we need window onload?

The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

Why script is at the bottom?

When you place your JavaScript at the bottom of your HTML body, it gives the HTML time to load before any of the JavaScript loads, which can prevent errors, and speed up website response time.

What is the difference between onload () and document ready () methods?

The onload executes a block of code after the page is completely loaded while $(document). ready(function) executes a block of code once the DOM is ready.


2 Answers

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 onload event.

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 return fail if the result is different than what you'd expect (i.e. what your design specifies) and return success when the result matches what you would expect. With onload they always return success.

Example 1

In this example, the code is expecting the image to be a certain width. If the code is wrapped in an onload event the width is correct, otherwise, it's not.

Demo: http://jsfiddle.net/ThinkingStiff/qUWxX/

HTML:

<div id="result"></div>
<img id='image' src="http://thinkingstiff.com/images/matt.jpg" />

Script:

document.getElementById( 'result' ).innerHTML 
    = document.getElementById( 'image' ).offsetWidth == 346 ? 'success': 'fail';

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.

enter image description here

Change that to "onDomReady" or "no wrap (body)":

enter image description hereenter image description here

Now press "Run" at the top left of the page:

enter image description here

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 onload it's corrent, without, it's not. Use the same instructions as before for this demo.

Demo: http://jsfiddle.net/ThinkingStiff/n7GWt/

HTML:

<div id="result"></div>
<div id="style"></div>

<script>
    window.setTimeout( function() { 
        document.getElementById( 'style' ).style.width = '100px'; 
    }, 1 );
</script>

Script:

document.getElementById( 'result' ).innerHTML 
    = document.getElementById( 'style' ).style.width ? 'success' : 'fail';

Example 3

Here's an example that uses no images or Javascript in the body, just CSS. Again, the results are different between onload and not.

Demo: http://jsfiddle.net/ThinkingStiff/HN2bH/

CSS:

#style {
    animation:             style 5s infinite;
        -moz-animation:    style 5s infinite;
        -ms-animation:     style 5s infinite;
        -o-animation:      style 5s infinite;
        -webkit-animation: style 5s infinite;
    border: 1px solid black;
    height: 20px;
    width: 100px;    
}

@keyframes             style { 0% { width: 100px; } 100% { width: 500px; } }
    @-moz-keyframes    style { 0% { width: 100px; } 100% { width: 500px; } }
    @-ms-keyframes     style { 0% { width: 100px; } 100% { width: 500px; } }
    @-o-keyframes      style { 0% { width: 100px; } 100% { width: 500px; } }
    @-webkit-keyframes style { 0% { width: 100px; } 100% { width: 500px; } }

HTML:

<div id="result"></div>
<div id="style"></div>

Script:

document.getElementById( 'result' ).innerHTML 
    = document.getElementById( 'style' ).clientWidth > 100 ? 'success' : 'fail';

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 onload event.

like image 68
ThinkingStiff Avatar answered Oct 12 '22 22:10

ThinkingStiff


Couple of different things going on.

  1. onload is called only after embedded content such as images is loaded. This means you can put code in onload that depends on that content being there.
  2. ready handlers are fired before that, when the DOM (ie internal structure) of your page is fully loaded. This isn't that different from putting it at the bottom, but one difference is that if someone navigates away from your page and then back, these handlers will fire again.

Technically scripts that run at the end of the document can use methods like getElementById to pull in elements that are already rendered. You may still want to put those in a ready or load handler for the above reasons. This isn't to say the scripts themselves shouldn't be at the bottom - there's still a benefit to perceived performance from having them there.

like image 27
Dan Avatar answered Oct 12 '22 23:10

Dan