Files
blog/themes/Ying/assets/js/modules/lazyload.js
T

93 lines
2.2 KiB
JavaScript
Raw Normal View History

2026-01-31 19:24:22 +08:00
(function() {
var defaults = {
2026-05-20 14:33:05 +08:00
offsetBottom: 100,
showTime: 1100,
queueInterval: 200
2026-01-31 19:24:22 +08:00
};
var observer;
function init(setting) {
defaults = Object.assign({}, defaults, setting || {});
2026-01-31 21:27:06 +08:00
if (observer) {
observer.disconnect();
observer = null;
2026-01-31 19:24:22 +08:00
}
2026-02-02 20:38:58 +08:00
if (!window.IntersectionObserver) {
loadAllImages();
return;
}
2026-01-31 21:27:06 +08:00
observer = new IntersectionObserver(function(entries, self) {
entries.forEach(function(entry) {
2026-05-20 14:33:05 +08:00
if (!entry.isIntersecting) return;
var img = entry.target;
loadImage(img);
self.unobserve(img);
2026-01-31 21:27:06 +08:00
});
}, {
2026-05-20 14:33:05 +08:00
rootMargin: "0px 0px " + defaults.offsetBottom + "px 0px",
threshold: 0.01
2026-01-31 21:27:06 +08:00
});
2026-02-02 20:38:58 +08:00
observeImages();
2026-01-31 19:24:22 +08:00
}
2026-05-20 14:33:05 +08:00
function getPendingImages() {
return document.querySelectorAll('img.lazyload[data-lazy-src], .post-content img[data-lazy-src]:not(.lazy-loaded)');
}
2026-02-02 20:38:58 +08:00
function observeImages() {
2026-05-20 14:33:05 +08:00
var images = getPendingImages();
2026-01-31 19:24:22 +08:00
images.forEach(function(img) {
2026-05-20 14:33:05 +08:00
observer.observe(img);
2026-01-31 19:24:22 +08:00
});
}
2026-05-20 14:33:05 +08:00
function markLoaded(img, callback) {
img.classList.add('lazy-loaded');
img.removeAttribute('data-lazy-src');
if (callback) callback();
}
2026-02-02 20:38:58 +08:00
function loadImage(img, callback) {
var src = img.getAttribute('data-lazy-src');
if (!src) {
if (callback) callback();
return;
}
2026-01-31 19:24:22 +08:00
2026-05-20 14:33:05 +08:00
img.decoding = 'async';
2026-01-31 19:24:22 +08:00
var temp = new Image();
2026-05-20 14:33:05 +08:00
temp.decoding = 'async';
temp.onload = function() {
2026-02-02 20:38:58 +08:00
img.src = src;
2026-05-20 14:33:05 +08:00
requestAnimationFrame(function() {
markLoaded(img, callback);
2026-02-02 20:38:58 +08:00
});
2026-01-31 19:24:22 +08:00
};
2026-02-02 20:38:58 +08:00
2026-01-31 19:24:22 +08:00
temp.onerror = function() {
2026-02-02 20:38:58 +08:00
img.src = src;
2026-05-20 14:33:05 +08:00
markLoaded(img, callback);
2026-01-31 19:24:22 +08:00
};
2026-02-02 20:38:58 +08:00
2026-01-31 19:24:22 +08:00
temp.src = src;
}
2026-02-02 20:38:58 +08:00
function loadAllImages() {
2026-05-20 14:33:05 +08:00
var images = getPendingImages();
2026-02-02 20:38:58 +08:00
images.forEach(function(img) {
loadImage(img);
});
2026-01-31 19:24:22 +08:00
}
window.lazyLoadInit = init;
2026-02-02 20:38:58 +08:00
window.lazyLoadRefresh = observeImages;
2026-01-31 19:24:22 +08:00
})();