If you’ve used any jQuery plugins in your time – and lord knows I used to live on jQuery plugins – then you’ve probably seen the example code tell you to wrap your plugin calls in a
$(window).load() but do you know what they are or how they’re different? Most people are very familiar with
$(document).ready() but not a lot of love is given to
Say hello to
The jQuery docs for
$(document).ready() say it best:
A page can’t be manipulated safely until the document is “ready”.
But what does “ready” mean? In the context of the
$(document).ready() function, “ready” means that the DOM (Document Object Model – the browser’s internal model of the markup on the page) is ready or fully constructed. Page rendering happens quickly to us but when it comes to code being executed on the page you always want to make sure that the DOM elements you are targeting with jQuery actually exist and are fully loaded (parents, children, and siblings). If you try to fire off a transition or a fade in/fade out on page load without wrapping it in a
$(document).ready() solves is also one of the reasons that loading all JS after all of your HTML and before the closing
<body> tag is a recommended best practice.
Have you ever seen code like this and wondered what it’s doing:
1 2 3
$(document).ready()? It’s actually right there. New jQuery developers aren’t familiar with this shorthand which is equivalent to wrapping a function in
$(document).ready() like this code:
1 2 3
Wrapping your jQuery in
$() has the same effect as
$(window).load() function is similar to
$(document).ready() but goes slightly further. Instead of waiting for just the DOM to be ready,
$(window).load() won’t fire until the entire page has finished loading. This means stylesheets, images, and any resources that are referenced immediately but may not have completed downloading by the time the DOM is ready.
Image sliders are pretty much the most popular jQuery plugin type there is and it’s a perfect example of where
$(window).load() comes in handy. Let’s say you have a series of images that will scroll in a slider automatically on page load. Let’s go further and say that you want the user to be able to take in and read and text contained in those images (text in images is bad form but there are some cases where it’s sort of acceptable) and/or viewing each image in order is important to understanding your page.
In a situation like the one described above the
<img /> tags may be on the page and the DOM may be fully loaded and ready but you don’t want to fire off any scripts to start timing and moving those images in your slider until every image in the set is finished downloading. If you wrap your code in
$(window).load() then you can fire off your slider safe in the knowledge that it won’t start sliding before all the images have loaded, potentially showing users blank or half loaded slides and making the images appear out of order and without context.
So there you have it. The difference between