Skip to content

Instantly share code, notes, and snippets.

@dannyvassallo
Last active December 29, 2015 16:10
Show Gist options
  • Save dannyvassallo/9291798cc742042b95bd to your computer and use it in GitHub Desktop.
Save dannyvassallo/9291798cc742042b95bd to your computer and use it in GitHub Desktop.
Lazyload JS
<img src="blank.gif" class="lazy" data-src="/images/full-size.jpg" width="240" height="152">
!function(window){
function loadImage($el, $fn) {
jQuery($el).attr('src', jQuery($el).attr('data-src'));
$fn ? $fn() : null;
}
function elementInViewport($el) {
var $rect = $el.getBoundingClientRect();
return ($rect.top >= 0 && $rect.left >= 0 && $rect.top <= (window.innerHeight || document.documentElement.clientHeight)
);
}
jQuery(document).ready(function() {
var images = [],
query = jQuery('img.lazy'),
processScroll = function() {
jQuery.each(images, function(i, img) {
if (elementInViewport(img)) {
loadImage(img, function () {
images.splice(i, 1);
});
}
});
};
query.each(function() {
images.push(this);
});
processScroll();
jQuery(window).bind('scroll', processScroll);
});
}(this);
!function(window){
var $q = function(q, res){
if (document.querySelectorAll) {
res = document.querySelectorAll(q);
} else {
var d=document
, a=d.styleSheets[0] || d.createStyleSheet();
a.addRule(q,'f:b');
for(var l=d.all,b=0,c=[],f=l.length;b<f;b++)
l[b].currentStyle.f && c.push(l[b]);
a.removeRule(0);
res = c;
}
return res;
}
, addEventListener = function(evt, fn){
window.addEventListener
? this.addEventListener(evt, fn, false)
: (window.attachEvent)
? this.attachEvent('on' + evt, fn)
: this['on' + evt] = fn;
}
, _has = function(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
;
function loadImage (el, fn) {
var img = new Image()
, src = el.getAttribute('data-src');
img.onload = function() {
if (!! el.parent)
el.parent.replaceChild(img, el)
else
el.src = src;
fn? fn() : null;
}
img.src = src;
}
function elementInViewport(el) {
var rect = el.getBoundingClientRect()
return (
rect.top >= 0
&& rect.left >= 0
&& rect.top <= (window.innerHeight || document.documentElement.clientHeight)
)
}
var images = new Array()
, query = $q('img.lazy')
, processScroll = function(){
for (var i = 0; i < images.length; i++) {
if (elementInViewport(images[i])) {
loadImage(images[i], function () {
images.splice(i, i);
});
}
};
}
;
// Array.prototype.slice.call is not callable under our lovely IE8
for (var i = 0; i < query.length; i++) {
images.push(query[i]);
};
processScroll();
addEventListener('scroll',processScroll);
}(this);​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment