JQuery Load vs Ready

There a many situations where you need to check if a page and its elements are available to update or alter via JQuery. Example include activating JQuery animations, reading the contents of an iframe or interacting with Flash.

There are two JQuery commands that should be part of every web developers tool kit when dealing with dynamic JQuery content.

The first is JQuery $(document).ready() handler.

E.g.
$(document).ready(function(){ //do stuff });

This function is great when all you need to do is check the DOM has been loaded. Using this function will allow other JQuery scripts to run as soon as the DOM has loaded so this is great for fast data only interactions or updates to content textual content.

The problem is $(document).ready() can't check for elements that are loaded after the DOM has loaded. This covers elements such as Flash SWF files, PDFs, MP3s, iframes and most importantly rendered images.

To fire a JQuery event after a web page is fully loaded use the $(window).load() handler.

E.g.
$(window).load(function () { // do stuff });

This method is a shortcut for .bind('load', handler).

Using this method is similar to using body onload="callfunction();" and will allow you to initiate JQuery events after the entire page and its content have been loaded in the browser.

There are some problems with $(window).load() and these issues need to be considered when using the method in your scripts. The issues are as follows:

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree
  • Can cease to fire for images that already live in the browser's cache

When checking to see if an image has loaded before initiating a JQuery function you could use a polling script to check the JavaScript Boolean .complete.

E.g.

<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
</head>

<body>
<div id="stats"></div>
<img src="http://farm4.staticflickr.com/3509/3926074532_35b2a15e9e_z.jpg?zz=1" id="img-example">
<script type="text/javascript">
var i = 0;
window.onload = createInterval();
function createInterval(){
intervalID=setInterval("readyCheck()",100);
}
function readyCheck(){
i++;
if($('#img-example').get(0).complete){
$('#stats').html("Loaded in: "+i+"00 ms");
clearInterval(intervalID);
//alert('loaded');
} else {
//alert('loading');

}
}
</script>
</body>
</html>

There are many load options available in JavaScript and JQuery so just use the approach that works for your content.