Unveil.js: load images on-the-go with this lightweight version of the Lazy Load plugin

You are probably already familiar with the Lazy Load, a jQuery plugin that loads images outside of viewport (visible part of web page) only when user scrolls to them.

This plugin is very helpful when dealing with long pages and/or a lot of images and makes the pages load faster.

Unveil.js

I found an handy jQuery plugin written by Luís Almeida that does exactly this job with just a few lines of js: Unveil.


(function( $ ) {
 $.fn.unveil = function () {
 var images = this, loaded, inview;

 this.one("unveil", function(){
 this.setAttribute( "src", this.getAttribute( "data-src" ) );
 this.removeAttribute( "data-src" );
 });

 function unveil () {
 inview = images.filter(function(){
 var $e = $(this),
 $w = $(window),
 wt = $w.scrollTop(),
 wb = wt + $w.height(),
 et = $e.offset().top,
 eb = et + $e.height();

 return eb >= wt && et <= wb;
 });

 loaded = inview.trigger("unveil");
 images = images.not( loaded );
 }

 $(window).scroll(unveil);
 unveil();

 return this;
 };
})( jQuery );

Usage

You just need to include images in this way:


<img data-src="image.jpg" src="loader.gif">

and call the the plugin to load images


$("img").unveil();