Delayed Loading of Images

Blog Projects
javascript jquery lazy load
HEADS UP! This article was written in 2008. Information provided might not be valid anymore and should be taken with a grain of salt.
Latest version of Lazy Load is not a drop in replacement to your webpage. New browsers load image even if you remove the src attribute with JavaScript. Now you must alter your html code. Put placeholder image into src attribute of your img tag. Real image url should be stored data-original attribute.

<img data-original=“img/example.jpg” src=“img/grey.gif”>
Good thing is you can now put all your JavaScript to the end of the page. If you want to support non JavaScript browsers there is an extra step. You must include original image inside <noscript> tag. For more information read the documentation.

Several people have asked me to add timeout option to Lazy Load plugin. As before, only images inside viewport would be loaded and page will come to ready state faster. However browser would load rest of the images automatically after specific amount of time.

I do not think it is necessary to add another configuration option for it. It all can be done with few lines of JavaScript.

Custom events

By default Lazy Load binds to scroll event. When window is scrolled plugin checks if any new images have become visible. For this case we want to use something different. We could use any of the normal jQuery events such as click or dblclick. But lets invent our own event. We will name it sporty.

  $(document).ready(function() {
         placeholder : "img/grey.gif",
         event : "sporty"

We could have used any event name such as go-grazy or beam-me-up. Now we could trigger loading of images with following code.


Timeout after page has finished loading

Normally we would throw all code inside $(document).ready(). However there is one catch. It launches code after DOM (or you could say HTML) is loaded and ready. We want to start our timeout countdown only after all elements of page (images etc) have been loaded.

 $(window).bind("load", function() {
     var timeout = setTimeout(function() { $("img").trigger("sporty") }, 5000);

So what we just did? Code waits for page to finish loading. It then waits for 5 seconds and triggers sporty event on all images. Because we told Lazy Load plugin to listen for sporty events rest of the images will now load.

Related entries: Preload Images Sequentially With jQuery, Lazy Load With Effects, Lazy Load Sideways, Lazy Load With Effects.

When asking a question include an URL to example page where the problem occurs. Even better is to make a Fiddle which demonstrates the problem. If you have longer code examples please use