94 lines
2.2 KiB
JavaScript
94 lines
2.2 KiB
JavaScript
(function() {
|
|
var defaults = {
|
|
offsetBottom: 100,
|
|
showTime: 1100,
|
|
queueInterval: 200
|
|
};
|
|
|
|
var observer;
|
|
|
|
function init(setting) {
|
|
defaults = Object.assign({}, defaults, setting || {});
|
|
|
|
if (observer) {
|
|
observer.disconnect();
|
|
observer = null;
|
|
}
|
|
|
|
if (!window.IntersectionObserver) {
|
|
loadAllImages();
|
|
return;
|
|
}
|
|
|
|
observer = new IntersectionObserver(function(entries, self) {
|
|
entries.forEach(function(entry) {
|
|
if (!entry.isIntersecting) return;
|
|
|
|
var img = entry.target;
|
|
loadImage(img);
|
|
self.unobserve(img);
|
|
});
|
|
}, {
|
|
rootMargin: "0px 0px " + defaults.offsetBottom + "px 0px",
|
|
threshold: 0.01
|
|
});
|
|
|
|
observeImages();
|
|
}
|
|
|
|
function getPendingImages() {
|
|
return document.querySelectorAll('img.lazyload[data-lazy-src], .post-content img[data-lazy-src]:not(.lazy-loaded)');
|
|
}
|
|
|
|
function observeImages() {
|
|
var images = getPendingImages();
|
|
|
|
images.forEach(function(img) {
|
|
observer.observe(img);
|
|
});
|
|
}
|
|
|
|
function markLoaded(img, callback) {
|
|
img.classList.add('lazy-loaded');
|
|
img.removeAttribute('data-lazy-src');
|
|
if (callback) callback();
|
|
}
|
|
|
|
function loadImage(img, callback) {
|
|
var src = img.getAttribute('data-lazy-src');
|
|
if (!src) {
|
|
if (callback) callback();
|
|
return;
|
|
}
|
|
|
|
img.decoding = 'async';
|
|
|
|
var temp = new Image();
|
|
temp.decoding = 'async';
|
|
|
|
temp.onload = function() {
|
|
img.src = src;
|
|
requestAnimationFrame(function() {
|
|
markLoaded(img, callback);
|
|
});
|
|
};
|
|
|
|
temp.onerror = function() {
|
|
img.src = src;
|
|
markLoaded(img, callback);
|
|
};
|
|
|
|
temp.src = src;
|
|
}
|
|
|
|
function loadAllImages() {
|
|
var images = getPendingImages();
|
|
images.forEach(function(img) {
|
|
loadImage(img);
|
|
});
|
|
}
|
|
|
|
window.lazyLoadInit = init;
|
|
window.lazyLoadRefresh = observeImages;
|
|
})();
|