Last active
November 29, 2023 18:39
-
-
Save danjac/9dd7e1487c358a9983b4595f22471908 to your computer and use it in GitHub Desktop.
HTML component for rendering image with fallback to placeholder
This file contains 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