Unveil2.js

Lightweight but rich lazy load plugin for jQuery

Source on GitHub

Image by Rosmarie Voegtli

Usage

Basic

Couldn't be easier. Include an image like you normally would, include the unveil2 script and initialize:

<img src="photo.jpg">

<script src="//code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="jquery.unveil2.min.js"></script>

<script>
    $('img').unveil();
</script>

Retina

Unveil2 can replace images with a retina variant if it detects a high DPI screen. Define a retina image as follows:

<img src="photo.jpg" data-src="photo.jpg|photo@2x.jpg">

Placeholder images

To replace images with a placeholder once they're not yet loaded, use the data-src-placeholder attribute:

<img src="photo.jpg" data-src-placeholder="placeholder.jpg" >

Note: Don't replace the original image in the src attribute with a placeholder image, since this will potentially mess with bots, scrapers and JavaScript disabled browsers. Unveil2 will tell the browser to stop loading the original image so it won't slow down the loading of the page.

CSS background images

Unveil2 can lazy load CSS background images:

<header data-src="bg.jpg|bg@2x.jpg">
<script>
    $('header').unveil();
</script>

Breakpoints

Specify larger images to be used on larger screen-widths by adding attributes and passing an array of breakpoints when invoking unveil2, for a true mobile-first experience:

<img src="small.jpg" data-src-md="medium.jpg" />
<script>
    $('img').unveil({
        breakpoints: [{
            minWidth: 768,
            attribute: 'data-src-md'
        }]
    });
</script>

Classes

During the lazy load lifecycle several classes are added to the lazy element:

Advanced example

<img src="http://loremflickr.com/450/300"
     data-src="http://loremflickr.com/450/300|http://loremflickr.com/900/600"
     data-src-md="http://loremflickr.com/750/500|http://loremflickr.com/1500/1000"
     data-src-lg="http://loremflickr.com/1050/700|http://loremflickr.com/2100/1400"
/>

<script src="//code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="jquery.unveil2.min.js"></script>

<script>
    $('img').unveil({
        offset: 100,
        throttle: 200,
        placeholder: 'http://placehold.it/500x300',
        breakpoints: [
            {
                minWidth: 768,
                attribute: 'data-src-md'
            },
            {
                minWidth: 1200,
                attribute: 'data-src-lg'
            }
        ],
        debug: true
    }).on('loading.unveil', function () {
        console.log('Unveiling', this);
    }).on('loaded.unveil', function () {
        console.log('Unveiled', this);
    });
</script>

For all available options, see API documentation.