Bagnall Software Consultants Ltd

Prioritised Image Loading

If you have a page or even a whole site hosted within one page, where much of the navigation and content loading is dynamic, you may want to prioritise the order of the image loading so that those images encountered first in the navigation of the site, are loaded first, and subsequent images can be loaded later at a lower priority. Using jQuery, this is a simple matter.

  1. For images you need immediately, use the attribute src='imagename.jpg'.
  2. for images for which you want to delay loading, use the attributes src='blank.gif' data-src='actualImage.jpg'. Where blank.gif is a 1x1px transparent gif.
  3. Add a class for example class='tier1' to the delayed images to determine the order in which they are loaded, for example tier1 may be those images you might see after one navigation event or click, tier2 may be those images you might see after another navigation event and so on.
  4. Use something like the following code to handle the load order. This requires that you are using jQuery.
    /* Load tier1 images */
    var $tier1=$('img.tier1');
    var tier1Len=$tier1.length;
    $tier1.each(function(index,element){
        var $this=$(this);
        $this.attr('src', $(this).attr('data-src'));
        if (index==tier1Len-1){
            /* Last tier1 image loaded, Start loading tier2 images */
            var $tier2=$('img.tier2');
            var tier2Len=$tier2.length;
            $tier2.each(function(index,element){
                var $this=$(this);
                $this.attr('src', $(this).attr('data-src'));
                if (index==tier2Len-1){
                    /* Last tier2 image loaded, Start loading tier3 images */
                    var $tier3=$('img.tier3');
                    $tier3.each(function(index,element){
                        var $this=$(this);
                        $this.attr('src', $(this).attr('data-src'));
                    });
                }
            });
        }
    });