Example of HTML markup and JS code to handle dark mode responsive images
<picture data-light-theme>
<source type="image/webp" srcset="images/light.webp">
<img src="images/light.webp" alt="Hero image"
:loading="theme() !== 'light' ? 'lazy' : null"
data-fallback-src="/path/to/fallback/" />
</picture>
<picture data-dark-theme>
<source type="image/webp" srcset="images/dark.webp">
<img src="images/dark.webp" alt="Hero image"
:loading="theme() !== 'dark' ? 'lazy' : null"
data-fallback-src="/path/to/fallback/" />
</picture>
<picture data-system-theme>
<source type="image/webp" srcset="images/dark.webp" media="(prefers-color-scheme: dark)">
<img src="images/light.webp" alt="Hero image"
:loading="theme() !== 'system' ? 'lazy' : null"
data-fallback-src="/path/to/fallback/" />
</picture>
document.querySelectorAll('img[data-fallback-src]:not([data-fallback-src=""])')
.forEach(img => img.onerror = () => {
img.onerror = null;
if (img.parentElement.nodeName === 'PICTURE') {
while (img.previousElementSibling) img.previousElementSibling.remove();
}
img.src = img.dataset.fallbackSrc;
});