Skip to content

Instantly share code, notes, and snippets.

@enrico-atzeni
Last active September 24, 2018 12:24
Show Gist options
  • Save enrico-atzeni/bb797d0831e8cfa26872fba383e274d6 to your computer and use it in GitHub Desktop.
Save enrico-atzeni/bb797d0831e8cfa26872fba383e274d6 to your computer and use it in GitHub Desktop.
javascript + jQuery advanced image lazyloader
// LAZY LOAD FOR IMAGES
// make it global so minifier can minify correctly
window.doLoadLazy = function(){};
var initLazyLoad = function(){
// set this as the preload you want to have to load image before they appear in the viewport
// accepts only INT
var offsetPreLoad = 200;
var itemsDone = [];
window.doLoadLazy = function ($lazyitems){
if(!$lazyitems)
return;
$lazyitems.each(function(index){
var $me = $(this);
// already done
if( !$me.attr('data-src') )
return;
var offTop = $me.offset().top,
maxVisibleScreen =
$(window).scrollTop() +
$(window).height();
var nearWindow = offTop - offsetPreLoad <= maxVisibleScreen;
if( nearWindow ){
// load from srcset
if( $me.attr('data-srcset') ){
$me.attr('srcset', $me.attr('data-srcset'));
$me.removeAttr('data-srcset');
}
// load image
$me.attr('src', $me.attr('data-src'));
$me.removeAttr('data-src');
// to remove already started items
itemsDone.push( index );
}
});
// if all done, empty the array
if(itemsDone.length >= $lazyitems.length){
$lazyitems = false;
itemsDone = 0;
}
};
// get images to lazy load
var $lazyitems = $('img[lazy=1], iframe[lazy=1]');
// call first time on page load to initialize
window.doLoadLazy( $lazyitems );
};
// ******************
// HOW TO USE
// ******************
// SETUP the DOM element
/*
requires:
<img src="/image.jpg" />
to become
<img data-src="/image.jpg" lazy="1" />
summary:
1) replace `src` && `srcset` with `data-src` && `data-srcset`
2) add `lazy="1"` attribute
optional:
you can add a base64 encoded grey point to fill the real image space,
but this needs `width` and `height` attributes to be set
eg:
<img src="/image.jpg" />
becomes:
<img data-src="/image.jpg"
lazy="1"
width="300"
height="250"
src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" />
*/
// Simple case ---------------
// call the lazyloader normally after page load
initLazyLoad();
// Advanced case -------------
// call the lazyloader manually after DOM changed (eg: next article appended to the DOM as with infinite-scroll library)
// explaination: if you change your DOM adding other imgs to lazy-load on scroll recall the global method passing an array of imgs
// get images to lazy load
var $lazyitems = $('img[lazy=1], iframe[lazy=1]');
// call to bind lazy load to this new images
window.doLoadLazy($lazyitems);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment