Assuming I have an image in my HTML code and I would like to show a spinner for as long as the image is loading. I could do so by loading the image in JavaScript and once loaded hide the spinner, for example:
async loadImage(src) {
return new Promise((resolve, reject) => {
let img = new Image()
img.onload = () => resolve(img)
img.onerror = reject
img.src = src
}).catch()
}
let image = document.getElementById('#image1')
loadImage(image.src).then(() => {
// Image loaded, spinner can be hidden.
})
Now I am trying to do the same with the HTML picture
element. Let's say I have the following HTML code:
<picture>
<source srcset="image2.webp" type="image/webp" />
<source srcset="image2.jpg" type="image/jpg" />
<img src="image2.jpg" />
</picture>
Using above JavaScript code it would load the source of the img
tag which is the JPG version. However the browser might not even choose to load the JPG version but the WebP version. I know of the currentSrc
property of images but this property only gets applied to the image once the image is loaded.
Basically I need to know which image the browser is loading before it is completely loaded. Does anyone have an idea how this can be achieved?