Files
PyPost/js/post/lazyimg.js
rattatwinko 20dbe662b0 updated styling.
+ syntax highlighter with prism.js trough a CDN
 + some better styling in general with CSS (now the body md gets placed in a div which you can modify)
 + first attempt on lazyloading with js for non lazyloadable things
2025-09-26 23:19:28 +02:00

55 lines
1.5 KiB
JavaScript

/**
* Still very experimental, does not yet work as intended.
* Will keep updating this.
*/
document.addEventListener("DOMContentLoaded", () => {
const images = document.querySelectorAll("img");
images.forEach(img => {
if (!img.dataset.src) {
img.dataset.src = img.src;
img.src = ""; // prevent immediate loading
}
});
const svgs = document.querySelectorAll("svg");
svgs.forEach(svg => {
if (!svg.dataset.svg) {
svg.dataset.svg = svg.innerHTML;
svg.innerHTML = ""; // clear for lazy-loading
}
});
const lazyElements = document.querySelectorAll("img[data-src], svg[data-svg]");
if ("IntersectionObserver" in window) {
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const el = entry.target;
if (el.tagName === "IMG" && el.dataset.src) {
el.src = el.dataset.src;
el.removeAttribute("data-src");
}
if (el.tagName === "SVG" && el.dataset.svg) {
el.innerHTML = el.dataset.svg;
el.removeAttribute("data-svg");
}
obs.unobserve(el);
}
});
}, { rootMargin: "100px" });
lazyElements.forEach(el => observer.observe(el));
} else {
// Fallback: load all immediately
lazyElements.forEach(el => {
if (el.tagName === "IMG" && el.dataset.src) el.src = el.dataset.src;
if (el.tagName === "SVG" && el.dataset.svg) el.innerHTML = el.dataset.svg;
});
}
});