Delayed Loading of Images

January 30th, 2008

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() { 
    $("img:below-the-fold").lazyload({
        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.

$("img").trigger("sporty");
 

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.

Sorry, comments are closed for this article.