Skip to content

Instantly share code, notes, and snippets.

@ThinhVu
Created May 9, 2019 12:57
Show Gist options
  • Save ThinhVu/db45117a71fa36a38b6564dd6aaa530c to your computer and use it in GitHub Desktop.
Save ThinhVu/db45117a71fa36a38b6564dd6aaa530c to your computer and use it in GitHub Desktop.
Image lazyload
function lazy(className, threshold) {
var imgs = [],
offset = screen.height + threshold,
targetEvent = 'wheel',
body = document.getElementsByTagName("body")[0];
var shownShow = function(img) {
var imgTop = img.getClientRects()[0].top,
viewportTop = -body.getClientRects()[0].top,
minDistance = viewportTop + offset,
isShouldShown = minDistance >= imgTop;
return isShouldShown && !img.hasAttribute('src');
}
var show = function(img) {
img.setAttribute('src', img.getAttribute('data-src'));
}
var removeShownImg = function() {
var temp = [];
for(var i=0; i<imgs.length; i++) {
if (!imgs[i].hasAttribute('src')) {
temp.push(imgs[i]);
}
}
imgs = temp;
}
var load = function(){
if (imgs.length) {
for (var i=0; i<imgs.length; i++) {
if (shownShow(imgs[i])) {
show(imgs[i]);
}
}
removeShownImg();
} else {
window.removeEventListener(targetEvent, load);
imgs = undefined;
}
}
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
imgs = document.getElementsByClassName(className);
window.addEventListener(targetEvent, load);
// trigger once to load image in current viewport.
setTimeout(load, 200);
}
});
}
// Ex :
// + in html : <img class='lz' data-src='https://host:post/img.jpg'>
// + and js : lazy('lz', 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment