Skip to content

Instantly share code, notes, and snippets.

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