mirror of
https://github.com/wah-su/mstickers.git
synced 2025-05-22 20:59:39 +05:00
add image lazy loading via observer API
This commit is contained in:
parent
728ca46595
commit
7ee2e1e54e
8 changed files with 81 additions and 99 deletions
|
@ -1,26 +1,35 @@
|
|||
const images = document.querySelectorAll("[data-image-id]");
|
||||
images.forEach((image, i) => {
|
||||
if (i < 4) {
|
||||
image.setAttribute("loading", "eager");
|
||||
|
||||
let observer = new IntersectionObserver(function(entries, self) {
|
||||
for (let entry of entries) {
|
||||
if (entry.isIntersecting) {
|
||||
let elem = entry.target;
|
||||
preload_image(elem);
|
||||
self.unobserve(elem);
|
||||
}
|
||||
}
|
||||
|
||||
const spinner = document.querySelector(
|
||||
`[data-spinner-id="${image.getAttribute("data-image-id")}"]`
|
||||
);
|
||||
|
||||
if (image.height > 0 && image.complete) {
|
||||
image.classList.remove("invisible");
|
||||
spinner.classList.add("invisible");
|
||||
return;
|
||||
} else {
|
||||
image.classList.add("invisible");
|
||||
spinner.classList.remove("invisible");
|
||||
}
|
||||
|
||||
image.addEventListener("load", () => {
|
||||
console.log("image " + image.getAttribute("data-image-id") + " loaded");
|
||||
image.classList.remove("invisible");
|
||||
spinner.classList.add("invisible");
|
||||
image.removeEventListener("load", this);
|
||||
});
|
||||
}, {
|
||||
rootMargin: '400px 400px 400px 400px'
|
||||
});
|
||||
|
||||
function preload_image(img) {
|
||||
img.src = img.dataset.imageSrc;
|
||||
img.setAttribute("loading", "eager")
|
||||
const id = img.dataset.imageId
|
||||
const spinner = document.querySelector(`[data-spinner-id="${id}"]`);
|
||||
|
||||
console.log(`Loading ${id}`);
|
||||
img.addEventListener("load", () => {
|
||||
console.log(`image ${id} loaded`);
|
||||
img.classList.remove("invisible");
|
||||
spinner.classList.add("invisible");
|
||||
img.removeEventListener("load", this);
|
||||
});
|
||||
}
|
||||
|
||||
images.forEach((image, i) => {
|
||||
if (i <= 5) {
|
||||
image.setAttribute("loading", "eager"); // should eager load first 6 (0-5) images
|
||||
}
|
||||
observer.observe(image)
|
||||
});
|
||||
|
|
|
@ -648,10 +648,6 @@ video {
|
|||
display: block;
|
||||
}
|
||||
|
||||
.inline {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
.flex {
|
||||
display: flex;
|
||||
}
|
||||
|
@ -697,10 +693,6 @@ video {
|
|||
width: 4rem;
|
||||
}
|
||||
|
||||
.w-24 {
|
||||
width: 6rem;
|
||||
}
|
||||
|
||||
.w-8 {
|
||||
width: 2rem;
|
||||
}
|
||||
|
@ -839,6 +831,11 @@ video {
|
|||
padding: 1rem;
|
||||
}
|
||||
|
||||
.px-2 {
|
||||
padding-left: 0.5rem;
|
||||
padding-right: 0.5rem;
|
||||
}
|
||||
|
||||
.px-4 {
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue