Last active
November 29, 2023 18:39
HTML component for rendering image with fallback to placeholder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CoverImage extends HTMLElement { | |
/* | |
Usage: | |
<cover-image placeholder="placeholder.jpg"> | |
<img src="cover.jpg" loading"lazy"> | |
</cover-image> | |
*/ | |
connectedCallback() { | |
const images = this.querySelectorAll("img"); | |
const placeholder = this.getAttribute("placeholder"); | |
images.forEach(image => { | |
const src = image.getAttribute("src"); | |
if (src !== placeholder) { | |
image.setAttribute("src", placeholder); | |
image.addEventListener( | |
"load", | |
() => { | |
image.setAttribute("src", src); | |
}, | |
{ once: true }, | |
); | |
image.addEventListener( | |
"error", | |
() => { | |
image.setAttribute("src", placeholder); | |
}, | |
{ once: true }, | |
); | |
} | |
}); | |
} | |
} | |
customElements.define("cover-image", CoverImage); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment