Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Lazy Image Loader: Quick draft of a lazy image loader using jQuery.
* @name lazyImageLoader
* @description A quick implementation of a lazy loading technique for images.
* @returns object {"load": load} (see below)
* @param $imageList jquery selector List of images
* @param options object Configuration options
* - "queue_size" the size of the "queue" you'd like to load when loader.load() is called
* - "data_attr" the name of the data-attribute on your image tag; ex: "<img data-src=" />"
* @name lazyImageLoader.load
* @description Loads one or many images.
* @returns undefined
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', $;
return true;
return {'load': load};
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;
<h1>Lazy Images Fiddle</h1>
<div class="list-container">
<ul id="list">
<li><img src="" alt=""></li>
<li><img src="" data-src="" alt=""></li>
<li><img src="" data-src="" alt=""></li>
<li><img src="" data-src="" alt=""></li>
<li><img src="" data-src="" alt=""></li>
<li><img src="" data-src="" alt=""></li>
<button class="next-btn">Load Next</button>
// Example
var $next = $('.next-btn'),
$imgs = $('#list li img[data-src]');
loader = lazyImageLoader($imgs);
function click(e){
$('#list').animate({'left': '-=642px'}, 300);
// attach click
$next.on('click', click);

This comment has been minimized.

Copy link
Owner Author

@aubricus aubricus commented Jul 15, 2013

This could use some improvement, like sending a dynamic queue size to load instead. In any case, I've created a fiddle for this as well:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment