Make images fade in as they load

This commit is contained in:
Svilen Markov 2024-05-12 03:18:55 +01:00
parent 82f51293df
commit 4beab6bcec
2 changed files with 40 additions and 0 deletions

View File

@ -217,6 +217,18 @@ img, svg {
max-width: 100%; max-width: 100%;
} }
img[loading=lazy].loaded:not(.finished-transition) {
transition: opacity .4s;
}
img[loading=lazy].cached:not(.finished-transition) {
transition: none;
}
img[loading=lazy]:not(.loaded, .cached) {
opacity: 0;
}
html { html {
scrollbar-color: var(--color-text-subdue) transparent; scrollbar-color: var(--color-text-subdue) transparent;
scroll-behavior: smooth; scroll-behavior: smooth;

View File

@ -142,6 +142,33 @@ function setupDynamicRelativeTime() {
}); });
} }
function setupLazyImages() {
const images = document.querySelectorAll("img[loading=lazy]");
if (images.length == 0) {
return;
}
function imageFinishedTransition(image) {
image.classList.add("finished-transition");
}
for (let i = 0; i < images.length; i++) {
const image = images[i];
if (image.complete) {
image.classList.add("cached");
setTimeout(() => imageFinishedTransition(image), 5);
} else {
// TODO: also handle error event
image.addEventListener("load", () => {
image.classList.add("loaded");
setTimeout(() => imageFinishedTransition(image), 500);
});
}
}
}
async function setupPage() { async function setupPage() {
const pageElement = document.getElementById("page"); const pageElement = document.getElementById("page");
const pageContents = await fetchPageContents(pageData.slug); const pageContents = await fetchPageContents(pageData.slug);
@ -152,6 +179,7 @@ async function setupPage() {
document.body.classList.add("animate-element-transition"); document.body.classList.add("animate-element-transition");
}, 150); }, 150);
setTimeout(setupLazyImages, 5);
setupCarousels(); setupCarousels();
setupDynamicRelativeTime(); setupDynamicRelativeTime();
} }