I am trying to load my images with a fade in effect that will be triggered once the image is loaded. I noticed that onload
works properly in Chrome, but in Firefox or Safari it is called some hundred miliseconds before the image is rendered, so any animation below that duration will be skipped.
I’ have been reading other questions, as:
- image.onload event and browser cache
- onload event in <img> tags firing prematurely in Firefox, not other browsers
Didn’t find an answer in any of them.
Here I created a snippet demonstrating the problem using Picsum heavy images —3000 x 3000—. Notice that, when opening this question on Chrome and running this snippet, on load the image is faded; but when opening this same question on Firefox or Safari the image is rendered without fade in.
const imgElement = new Image();
const rootElement = document.getElementById("root");
rootElement.append(imgElement);
imgElement.className = "image";
imgElement.src = "https://picsum.photos/3000/3000";
imgElement.onload = function () {
imgElement.classList.add("loaded");
};
.image {
border: 2px solid gray;
max-width: 100%;
opacity: 0;
transition: opacity 0.3s ease;
}
.image.loaded {
opacity: 1;
}
<div id="root"></div>
I don’t think also that it is related to the browsers cache, as is pointed out [here][5], because we are rendering a new image every time.
Any idea will be welcome!