Detect img tag onLoad even if it's cached
When using the onLoad$ property on an <img> tag in a Qwik component, you might encounter an issue where the onLoad$ event doesn't fire when the image is already cached in the browser.
In that case the onLoad$ logic is not being triggered.
This behavior is observed during normal navigation, but not when browser caching is disabled, indicating the cache's impact on the event.
The key point here is to get hold of a DOM element to detect onLoad correctly.
Basic example
import { component$, useSignal, useVisibleTask$ } from '@builder.io/qwik';
export default component$(() => {
const imgRef = useSignal<HTMLImageElement>();
useVisibleTask$(() => {
imgRef.value!.decode().then(() => {
alert('loaded and ready!');
});
});
return (
<section>
<img
ref={imgRef}
src="/logos/qwik-logo.svg"
height={200}
width={200}
/>
</section>
);
});