97 lines
2.9 KiB
JavaScript
97 lines
2.9 KiB
JavaScript
(function() {
|
|
var defaults = {
|
|
showTime: 800,
|
|
offsetBottom: 0,
|
|
offsetTopm: 50,
|
|
onLoadBackEnd: function (index, dom) { },
|
|
onLoadBackStart: function (index, dom) { }
|
|
};
|
|
|
|
var observer;
|
|
|
|
function init(setting) {
|
|
defaults = Object.assign({}, defaults, setting || {});
|
|
|
|
// Reset observer for PJAX support
|
|
if (observer) {
|
|
observer.disconnect();
|
|
observer = null;
|
|
}
|
|
|
|
// Initialize IntersectionObserver
|
|
observer = new IntersectionObserver(function(entries, self) {
|
|
entries.forEach(function(entry) {
|
|
if (entry.isIntersecting) {
|
|
var img = entry.target;
|
|
showImg(img);
|
|
self.unobserve(img);
|
|
}
|
|
});
|
|
}, {
|
|
rootMargin: defaults.offsetTopm + "px 0px " + defaults.offsetBottom + "px 0px"
|
|
});
|
|
|
|
processImages();
|
|
}
|
|
|
|
function processImages() {
|
|
if (!observer) {
|
|
init(); // Auto-initialize if not ready
|
|
}
|
|
// Expanded selector to catch more images
|
|
var images = document.querySelectorAll('img.lazyload, img:not(.blog-img):not([data-comp])');
|
|
images.forEach(function(img) {
|
|
// Check if already processed or has data-lazy-src
|
|
if (img.getAttribute('data-lazy-src')) {
|
|
// Already setup for lazy load, just observe
|
|
observer.observe(img);
|
|
} else if (img.getAttribute('src')) {
|
|
// Convert to lazy load
|
|
var src = img.getAttribute('src');
|
|
img.setAttribute('data-lazy-src', src);
|
|
img.setAttribute('src', 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==');
|
|
observer.observe(img);
|
|
}
|
|
});
|
|
}
|
|
|
|
function showImg(dom) {
|
|
if (dom.getAttribute('data-comp')) return;
|
|
dom.setAttribute('data-comp', 'true');
|
|
|
|
var src = dom.getAttribute('data-lazy-src');
|
|
if (!src) return;
|
|
|
|
// Create a temporary image to preload
|
|
var temp = new Image();
|
|
temp.onload = function() {
|
|
// Prepare for transition
|
|
dom.style.opacity = 0;
|
|
dom.style.transition = "opacity " + (defaults.showTime / 1000) + "s ease-in-out";
|
|
|
|
// Swap source
|
|
dom.setAttribute('src', src);
|
|
|
|
// Force reflow
|
|
void dom.offsetWidth;
|
|
|
|
// Fade in
|
|
dom.style.opacity = 1;
|
|
};
|
|
temp.onerror = function() {
|
|
// On error, show anyway
|
|
dom.setAttribute('src', src);
|
|
dom.style.opacity = 1;
|
|
};
|
|
temp.src = src;
|
|
}
|
|
|
|
function tryAgain() {
|
|
processImages();
|
|
}
|
|
|
|
window.lazyLoadInit = init;
|
|
window.lazyLoadAgain = tryAgain;
|
|
|
|
})();
|