Skip to main content

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. Examples include activating JQuery animations, reading the contents of an iframe or interacting with images.

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.

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

The recommended shorthand way of doing this is via a simple closure.

$(function() {
  // do stuff.
});

This function is great when you need to check the DOM has been loaded and trigger updates to the DOM content.

The equivalent native JavaScript for this JQuery function can be written as follows:

window.addEventListener('DOMContentLoaded', (event) => {
    // do stuff.
});

The problem is $(document).ready() can't check for elements that are loaded after the DOM has loaded. This covers elements such as iFrames, videos, 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 contents have been loaded in the browser.

The equivalent native JavaScript for this JQuery function can be written as follows:

window.addEventListener("load", (event) => {
  // do stuff
});

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 and 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.

<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 use the approach that works for your content.