hexo-lazyload-image-modified
Version:
a hexo plugin which is used to have all images support lazyload, with the help of this functionality, it will improve lots of the loading proformance.
49 lines (41 loc) • 1.11 kB
JavaScript
(function (window) {
var images = Array.prototype.slice.call(document.querySelectorAll('img[data-original]'));
function elementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= -rect.height
&& rect.left >= 0
&& rect.top <= (window.innerHeight || document.documentElement.clientHeight) * 2
);
}
function loadImage(el, fn) {
var img = new Image()
var src = el.getAttribute('data-original');
img.onload = function () {
el.src = src;
fn ? fn() : null;
$(el).removeClass('blur-img')
};
img.src = src;
}
function processImages() {
for (var i = 0; i < images.length; i++) {
if (elementInViewport(images[i])) {
loadImage(images[i], function () {
images.splice(i, i);
});
}
}
;
}
function throttle(method, context) {
clearTimeout(method.tId);
method.tId = setTimeout(function () {
method.call(context);
}, 500);
}
processImages();
window.addEventListener('scroll', function () {
throttle(processImages, window);
});
})(this);