Lazy loading images with JavaScript

Nov 23, 2013

Lazy loading images upon DOM ready with the help of jQuery:

$(function(){
    $('img.to-load').each(function(index, object) {
        $(this).attr('src', $(this).data('src'));
    });
});

There are both server side and client side solutions:

  • Google’s PageSpeed module:
    • URL: https://developers.google.com/speed/pagespeed/module/filter-lazyload-images
    • Well, we all at least heard of this module, that is currently available for Apache and Nginx, but it seems that the great job they did at Google, it goes even further as they built a lazy load module within it. This is awesome! **BUT, **The problem is that if you run Nginx (like I do) and don’t have already Nginx compiled with support for Page Speed module, you’ll have to uninstall current instance of Nginx and build it again, which requires time and server downtime, which not many people can afford to do so… unless you’re using Tengine. https://github.com/pagespeed/ngx_pagespeed#how-to-build
    • It would’ve been great to manage this lazy loading feature from within Nginx, and avoid loading more js code into the platform, but that is not the proper choice for now.
  • LazyLoad by tuupola
    • URL: https://github.com/tuupola/jquery_lazyload
    • Searching the web, and a little bit with bower, I have found this library that is still maintained, which is great. Not only that is serves the purpose, but it also comes with solutions to common problems when trying to optimize image loading for different devices, so, GREAT!
  • Unveil by luis-almeida
  • LazyLoad by vvo
    • **URL: **https://github.com/vvo/lazyload
    • Quote: Lazyload images, iframes, widgets with a standalone JavaScript lazyloader ~1kb
    • Well, this is a good alternative to the ones above, and it seems to go even further by giving lazy load support for not only images, but iframes and widgets as well.

Now you decide what to try, and if you have any comments about this matter, please do share. I personally have implemented the LazyLoad by tuupola, and so far everything is going great.

Tags