fixed bug
This commit is contained in:
1 parent
7b945786ed
commit
54b18039e3
21 files changed
+2363
-408
No files matched your search
@@ -0,0 +1,88 @@
|
||||
(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 || {});
|
||||
|
||||
// Initialize IntersectionObserver
|
||||
if (!observer) {
|
||||
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() {
|
||||
var images = document.querySelectorAll('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;
|
||||
|
||||
})();
|
||||
Reference in new issue
Block a user