At last check (Dec 2016), images make up over 50% of the top 1000 web sites’ total size, and dissecting your own site probably yields similar numbers. When it comes to dramatically improving page loading times then (which has countless benefits, from decreased bounce rates, improved conversations, to higher Google rankings), it makes sense to start with your site’s images first. Tools such as Online Image Optimizer help reduce your large images’ size without any noticeable degradation in quality, though the images are still loaded indiscriminately nonetheless. That’s where lazy loading images come in- as the name suggests, the idea is to asynchronously or even conditionally load images on a page only when they appear in the browser’s viewport, so some images are not loaded at all if the user doesn’t get that far on the page. You’ve most likely seen this in action on many blogs already. In this post we’ll look at 5 of the best scripts to lazy load images, simply and automatically without much afterthought required from you. They are listed in increasing order of features depending on your needs.
#1 Lazy Load Images after page has loaded using just 7 lines of JavaScript
The first method of lazy loading images consist of just 7 lines of JavaScript, and is sufficient in optimizing the initial download time of the page while still loading all images automatically. Simply modify the images you wish to lazy load so their “
src
” property points to a blank or “loading spinner”, and use a custom attribute such as data-src
to store the reference to the real image that should be lazily loaded:
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="realimage.gif" />
<img src="spinner.gif" data-src="realimage2.gif" />
In case you’re wondering, the original “src” property in the first img tag above simply points to a Base 64 transparent gif (tip: You can use a tool such as Image to Base 64 Converter to convert any image into Base 64 format). Then at the bottom of your page add the following JavaScript to scan through all images on the page and lazy load those with a data-src
attribute defined after the page has fully loaded:
<script>
window.addEventListener('load', function(){
var allimages= document.getElementsByTagName('img');
for (var i=0; i<allimages.length; i++) {
if (allimages[i].getAttribute('data-src')) {
allimages[i].setAttribute('src', allimages[i].getAttribute('data-src'));
}
}
}, false)
</script>
The key action that makes this optimization work is loading the real images after the page has loaded. By relegating the target images to load asynchronously after the page has loaded, the page, well, loads faster, and actions that depend on the page having finished loading to fire such as Google Ads, many third party scripts, etc will fire sooner. Google most likely will also evaluate the page as having a decreased loading time, which helps with your SEO.
In Summary:
Pros of this technique:
- Simple as pie to implement
- Only 7 lines of JavaScript unminified
Cons:
- Still loads every image on the page whether or not they’re seen.
- If your initial page contents take a long time to load, there is a long waiting time before users can see the lazily loaded images.
#2 Echo.js Lazy Image Loading JavaScript
Echo.js is the next logical candidate to consider if you’re looking for a compact, vanilla JavaScript that actually lazily loads images on demand, when they become visible in the user’s screen. Only 1kb minified, the script focuses squarely on lazy loading images, without any bells or whistles.
Here’s an example implementation of the script:
<img src="img/blank.gif" alt="Photo" data-echo="img/photo.jpg" />
<script src="dist/echo.js"></script>
<script>
echo.init({
callback: function (element, op) {
console.log(element, 'has been', op + 'ed')
}
});
// echo.render(); is also available for non-scroll callbacks
</script>
In Summary:
Pros of this technique:
- No Library dependencies such as jQuery
- Only 1kb minified in size
- Can also lazy load background images
- Supports callback after an image has been lazily loaded
Cons:
- No built in “loading gif” or image transition when revealing the images, though you can easily implement one yourself using the callback function.
- Doesn’t work with images inside a scrollable DIV
#3 BLazy.js Lazy Image Loading JavaScript
At 1.6kb minified, BLazy is slightly larger than Echo.js, though you get a lot of added features from those extra bytes. Apart from being able to lazy load images and background images, you can also serve up different lazy images based on device sizes, such as one image for 480px or less devices, and another for 720px or less etc. You can also load high resolution images for retina display capable devices. And finally, lazy loading inside scrollable containers also works. An example basic implementation:
<img class="b-lazy" src="blank.gif" alt="alt-text" data-src="image.jpg" />
<script src="blazy.js"></script>
<script>
// Initialize
var bLazy = new Blazy();
</script>
In Summary:
Pros of this technique:
- A manageable 1.6kb in size minified
- No Library dependencies such as jQuery
- Apart from lazy loading images, can also serve up different images based on device width and for retina devices.
- Works with images inside a scrollable container
Cons:
- No built in “loading” or image transition when revealing the images, though you can easily implement one yourself using the callback function or by defining a specific CSS class containing the CSS3 transition effects to be applied.
#4 jQuery Lazy Image Loading Plugin
We now venture into jQuery plugins territory. If your site already uses jQuery, then there’s no reason not to consider a jQuery plugin to lazy load your images; otherwise bear in mind the 32kb hit that jQuery itself (minified) adds to your page (although it most likely will be cached). With that said, jQuery Lazy is a compact jQuery Lazy Image plugin (1.27kb minified) that differentiates from the above scripts in a few ways. Most notable about this script is the ability to lazy load images in both a vertical and horizontal layout, which is useful if you have a scrollable horizontal “carousel of images”, for example. Also, the plugin comes with additional, optional plugins (another 2.27kb in size total) you can add on to lazy load other types of content, such as IFRAME content, JavaScripts, AUDIO and VIDEOS. And finally, there are CDN hosted versions of the plugins available so you don’t have to upload any files to your server. Here’s a sample implementation:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery.lazy/1.7.4/jquery.lazy.min.js"></script>
<img class="lazy" src="img/blank.gif" alt="Photo" data-src="http://pipsum.com/800x500.jpg" />
<img class="lazy" src="img/blank.gif" alt="Photo" data-src="http://pipsum.com/400x500.jpg" />
<img class="lazy" src="img/blank.gif" alt="Photo" data-src="http://pipsum.com/700x500.jpg" />
<script>
$(function() {
$('.lazy').lazy();
});
</script>
In Summary:
Pros of this technique:
- Supports CDN hosting so you don’t have to upload any files to your server
- Lazy loads images in both vertical and horizontal layouts, plus inside scrollable containers
- Supports a loading animation and simple jQuery transitions such as Fade In out of the box
- With an additional plugin can lazy load other media types such as IFRAME content, videos etc
Cons:
- Requires jQuery as a dependency
#5 Lazy Load XT jQuery plugin
Last but certainly not least, we arrive at Lazy Load XT. Get past the unusual name, and herein lies a lazy loading plugin packed to the rim with features, by way of add-ons (not to be confused with additional plugins). The stock script (at around 3kb minified) already supports lazy loading images inside scrollable containers, both vertical and horizontal layouts, and “infnite scroll” set ups. Where things really get interesting is when you throw in an add on (either another .js or .css file). Want to show a default animated spinner while images are being loaded? Just reference another .css file. Want a fancy transition to introduce the lazily loaded image with style? Animate.css works with Lazy Load XT to provide a myriad of effects. How about serve up different images based on device size? The “response image” add-on will enable that. As always, here’s an example basic implementation:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.lazyloadxt/1.0.0/jquery.lazyloadxt.min.js"></script>
<img src="img/blank.gif" alt="Photo" width="800px" height="500px" data-src="http://pipsum.com/800x500.jpg" />
<img src="img/blank.gif" alt="Photo" width="800px" height="500px" data-src="http://pipsum.com/800x500.jpg" />
<img src="img/blank.gif" alt="Photo" width="800px" height="500px" data-src="http://pipsum.com/800x500.jpg" />
In Summary:
Pros of this technique:
- Supports CDN hosting of the core and add on files, so you don’t have to upload any files to your server
- Lazy loads images in scrollable containers, horizontal and infinite scroll layouts
- Supports a loading animation and Animate.css transitions such as Bounce In via “add-ons”
- With an additional add-on can also lazy load other media types such as IFRAME content, videos etc
Cons:
- Requires jQuery 1.7+ as a dependency
- Depending on the features you need, you may need to reference multiple “add-on” files.
#6 a3 Lazy Load WordPress Plugin Bonus
A lot of you have asked me for a good image lazy load plugin for WordPress, and for those users, I definitely recommend a3 Lazy Load. It’s what I’m using on this blog, and it works great out of the box. It’s free, lightweight, and doesn’t require any configuration to get up and running. What else can you ask for?
To install it, search for the plugin by name “a3 lazy load” inside your WordPress dashboard, or click on the link above to manually download it first.
Conclusion
With images constituting the biggest factor bogging down webpages’ download times, lazy loading images is an approach that should pay dividends in spades for many a sites. The 5 solutions we just covered provides you with a stepping stone of increasingly feature rich, plug-and-play lazy loading solutions to cover all the basis. Enjoy!
Hello and thanks for reviewing my plugin! 🙂
Just to be complete on this, jQuery Lazy is even capable of loading images inside containers. Just use ‘appendScroll’ config parameter.
Thanks, I’ve updated the summary to include “inside scrollable containers”. 🙂