Skip to content

Instantly share code, notes, and snippets.

@HakurouKen
Last active August 29, 2015 14:11
Show Gist options
  • Save HakurouKen/90d2a0ab542ab9056299 to your computer and use it in GitHub Desktop.
Save HakurouKen/90d2a0ab542ab9056299 to your computer and use it in GitHub Desktop.
A simple lazyload plugin for Zepto/jQuery
(function($){
$.fn.lazyload = function(options){
var $container = options.$container,
$window = $(window),
elems = [];
options = $.extend({
attr: 'data-lazyload',
$container: $window,
advance: 100,
placeholder: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgYAAAAAMAASsJTYQAAAAASUVORK5CYII=',
callback: function(){}
},options);
$(this).find( '[' + options.attr + ']').each(function(i,elem){
var $self = $(this);
$self.attr('src',options.placeholder);
elems.push({
$elem : $self,
tag : this.nodeName.toLowerCase(),
top : $self.offset().top - options.advance,
url : $self.attr(options.attr)
});
});
var handler = function(callback){
var h = $container.height(),
top,
i, l, cur, $o;
if ( $container[0] === $container[0].window ) {
top = $window.scrollTop();
} else {
top = $container.offset().top;
}
for( i = 0 , l = elems.length; i < l ; i++ ){
cur = elems[i];
$o = cur.$elem;
if( cur.top < h + top ){
if( cur.url ){
if (cur.tag === "img") {
$o.attr("src", cur.url);
} else {
$o.load(url, {}, function(){});
}
$o.attr(options.attr,null);
}
elems.splice(i,1);
i--;
l--;
$.isFunction(callback) && callback($o);
}
}
};
handler(options.callback);
$container.on('scroll',handler);
$window.on('resize',handler);
};
})(Zepto);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment