< Dave Taylor

jquery.lazyLoader. Semantic, organic responsive images

There's been a fair few ways in which people have been trying to achieve responsive images. Here's another angle at the same problem. The idea is to keep the process as organic as possible and not rely on tricking the browser in to submission to support responsive <img> tags (maybe one day we won’t have to).

This doesn't have to be used for responsive images. If you just want to lazy-load images on the fly this can also be very helpful.

This is my contribution to the toolset, I think it has it's place but let me know if I've missed something obvious. It’ highly likely ;)

Example

Resize the screen, the image below will jump in sizes between 0px, 600px and 900px

people

Build Status

Converts links either pointing to an image src or with a data-img attribute to images with that source.

Install

Download the latest version and include in your page alongside jQuery.

Usage

With the following markup

<div id="#lazy">
    <a href="myimage.jpg">my image</a>
</div>

You run the plugin on the links

$('#lazy a').lazyLoader();

Examples

<a href="myimage.jpg">my image</a>

converts to

<img src="myimage.jpg" alt="my image" />

and with data attribute:

<a href="mypage.html" data-img="myimage.jpg">my image</a>

converts to

<img src="myimage.jpg" alt="my image" />

Responsive images

If you want to dynamically load images dependent on the screen dimensions then you can use the following.

<a href="myimage.jpg" 
   data-img768="myimage-768.jpg" 
   data-img990="myimage-990.jpg" 
>my image</a>

$('a').lazyLoader({
    steps: [768,990] // this must be sorted correctly
});

Or it also supports dynamic urls so you don't need all those data attributes.

<a href="myimage.jpg">my image</a>

$('a').lazyLoader({
    img: function(url, windowWidth) {
        if (windowWidth >= 768){
            return url.replace(/.(jpg|gif|png)$/i, '-mega.$1'); 
        } else {
            return url;
        },
        steps: [768,990] // leave this out if you just want it to run once
    }
});

This function appends "-mega" on to the end of the url if the windowWidth is greater than or equal to 768.

<img src="myimage-mega.jpg" alt="my image" />

Detecting When All Images Have Loaded

$('[rel="image"]').on('imagesLoaded', function(ev){
    // all images have been loaded
});

Test Suite

To run the test suite, you need node and npm

$ npm install
$ npm test