This websites home page has a number of 'logo' type images below the fold which are not critical to load immediately.  We can wait until the page has rendered before loading them.

Why bother?

  • Fast page load is good for SEO
  • Fast page load is good for UX
  • Fast page load is crucial for slow internet connections
  • It's easy to do!

Here's how I do it:


<img class="my-lazy-load" src="/path/to/1x1.png" data-src="http://example.com/path/to/image.png">
    

$(document).ready(function(){
    $('img.my-lazy-load').each(function(){
        $(this).attr('src', $(this).data('src'));
    });
});
    

I add the class 'my-lazy-load' to each img tag I want to lazy load, so it is easy to select them with jQuery.

I set the src value to a 1px by 1px image. This keeps the markup valid and just loads a tiny image once, however many lazy loading images we have...

 I add the real image path to a data-src attribute.  This way the real image is not loaded immediately, but we know what it should be...

Finally on the document ready event, we take the data-src value for each img tag and add it to the src value - and the real image downloads... Simples.

UPDATE:

You could use a data uri instead of a 1x1.png - this does not require any downloads and is about 30 bytes smaller :-)


<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="http://example.com/path/to/image.png" class="my-lazy-load">
    
Loading comments...
';