Skip to content

Instantly share code, notes, and snippets.

@aubricus
Last active October 1, 2015 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aubricus/2053534 to your computer and use it in GitHub Desktop.
Save aubricus/2053534 to your computer and use it in GitHub Desktop.
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="http://placehold.it/10x10 />"
*/
/**
* @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', $img.data(data_attr));
}
return true;
}
return {'load': load};
};
<style>
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;
}
</style>
<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>
// 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);
@aubricus
Copy link
Author

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:

http://jsfiddle.net/aubricus/2UntA/

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