gpttemp
This commit is contained in:
72
code/public/static/js/lazy.js
Normal file
72
code/public/static/js/lazy.js
Normal file
@@ -0,0 +1,72 @@
|
||||
(function () {
|
||||
if (window.__LAZY_LOADER_READY__) return;
|
||||
|
||||
const hasIO = "IntersectionObserver" in window;
|
||||
|
||||
function applyBg(el) {
|
||||
const src = el.getAttribute("data-src");
|
||||
if (src) el.style.backgroundImage = `url(${src})`;
|
||||
el.classList.remove("lazyload-bg");
|
||||
el.removeAttribute("data-src");
|
||||
}
|
||||
|
||||
function applyImg(img) {
|
||||
const src = img.getAttribute("data-src");
|
||||
const srcset = img.getAttribute("data-srcset");
|
||||
const sizes = img.getAttribute("data-sizes");
|
||||
|
||||
if (sizes) img.setAttribute("sizes", sizes);
|
||||
if (srcset) img.setAttribute("srcset", srcset);
|
||||
if (src) img.setAttribute("src", src);
|
||||
|
||||
img.classList.remove("lazyload-img");
|
||||
img.removeAttribute("data-src");
|
||||
img.removeAttribute("data-srcset");
|
||||
img.removeAttribute("data-sizes");
|
||||
}
|
||||
|
||||
function observe(elements, callback, options) {
|
||||
if (!elements || elements.length === 0) return;
|
||||
|
||||
// 兜底:不支持 IO 直接加载
|
||||
if (!hasIO) {
|
||||
elements.forEach(callback);
|
||||
return;
|
||||
}
|
||||
|
||||
const obs = new IntersectionObserver((entries, observer) => {
|
||||
entries.forEach(entry => {
|
||||
if (!entry.isIntersecting) return;
|
||||
callback(entry.target);
|
||||
observer.unobserve(entry.target);
|
||||
});
|
||||
}, options);
|
||||
|
||||
elements.forEach(el => obs.observe(el));
|
||||
}
|
||||
|
||||
function scan(root) {
|
||||
const ctx = root || document;
|
||||
|
||||
observe(
|
||||
ctx.querySelectorAll(".lazyload-bg"),
|
||||
applyBg,
|
||||
{ rootMargin: "400px 0px", threshold: 0.01 }
|
||||
);
|
||||
|
||||
observe(
|
||||
ctx.querySelectorAll(".lazyload-img"),
|
||||
applyImg,
|
||||
{ rootMargin: "200px 0px", threshold: 0.01 }
|
||||
);
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
scan(document);
|
||||
});
|
||||
|
||||
// 给“加载更多/分页追加 DOM”使用
|
||||
window.lazyScan = scan;
|
||||
|
||||
window.__LAZY_LOADER_READY__ = true;
|
||||
})();
|
||||
Reference in New Issue
Block a user