Lazy Image Loding

Quick implementation of some lazy image loading.

by Aubrey Taylor

HTML

<h1>Lazy Images Fiddle</h1>
<div class="list-container">
<ul id="list">
     <li><img src="http://placehold.it/640x320" alt=""></li>
     <li><img src="" data-src="http://placehold.it/640x320" alt=""></li>
     <li><img src="" data-src="http://placehold.it/640x320" alt=""></li>
     <li><img src="" data-src="http://placehold.it/640x320" alt=""></li>
     <li><img src="" data-src="http://placehold.it/640x320" alt=""></li>
     <li><img src="" data-src="http://placehold.it/640x320" alt=""></li>
</ul>
</div>
<button class="next-btn">Load Next</button>

CSS

html {
    font-family: sans-serif;
}
h1 {
    margin: 0;
    padding: 0;
    margin-bottom: .75em;
}
ul, ol, li {
    list-style: none;
    padding: 0;
    margin: 0;
}

.list-container {
    position: relative;
    height: 320px;
}

#list {
    width: 4480px;
    height: 320px;
    position: absolute;
    top: 0;
    left: 0;
}

#list li {
    float: left;
    margin-left: 2px;
}

.next-btn {
    display: block;
    margin-top: 10px;
}

JavaScript

(function(window, $){
var lazyImageLoader = function($imgs, options){
    options = options || {};
    var queue_size = options.queue_size || 1;
    var data_attr  = options.data_attr  || 'src';
    var imgArr     = $.makeArray($imgs);

    function load(){
        if(imgArr.length === 0) return false;
        
        // grab / remove img elements from our array
        var queue = imgArr.splice(0, queue_size),
            len   = queue.length -1,
            i     = -1;
        
        // load images by replacing src with value in data-src
        while(i++ < len) {
            var $img = $imgs.filter(queue[i]);
            $img.attr('src', $img.data(data_attr));
        }
        
        return true;
    }
    
    return {'load': load};
};
    
    
// Example
var $next = $('.next-btn'),
    $imgs = $('#list li img[data-src]');
    loader = lazyImageLoader($imgs);

function click(e){
    loader.load();
    $('#list').animate({'left': '-=642px'}, 300);
}

// attach click
$next.on('click', click);

})(window, window.jQuery)