The title pretty much summarizes the question. For example, we have the following snippet:
return new Promise(resolve =>
let img = new Image();
img.addEventListener('load', () => resolve());
)
but the src of the image will go through multiple redirects before actually producing a 200 and loading the image.
When will the event listener be invoked? Will it be invoked on the first call to the first URL? Or will it go through the entire redirection chain and trigger only at the end?
How could this be tested?
CodePudding user response:
I've used express code like this:
app.get("/image/:count", async (req, res) => {
// get count from the param
const count = Number(req.params.count);
// wait 500 ms
await new Promise((r) => setTimeout(r, 500));
// if count if 4 return the actual file
if (count === 4) {
return res.sendFile(path.join(__dirname, "public", "file.png"));
}
// else redirect with count 1
res.redirect("/image/" (count 1));
});
And frontend code
// start timer
console.time('image')
// create image
let img = new Image();
// add listener and print time passed when loaded
img.addEventListener('load', () => console.timeEnd('image'));
// set source
img.src = './image/1'
Console output is:
image: 2765.442138671875 ms
So yes, it will finish when it get the image after many redirects
You can see it also in the network tab
It will follow 20 redirects before throwing an error
You can check your self here
CodePudding user response:
The event happen when the image is full loaded, so after all the redirects.
You can test with this code:
const pic = document.querySelector('#pic')
pic.addEventListener('load', () => {
console.log('after full load', pic.offsetHeight)
})
<img id="pic" src="http://www.vista.it/assets/img/bg-aside.jpg" />
In the example we have a redirect to https://
To make even clear adjust the network speed with the browser inspector to something slow (eg slow 3G) and you will see event fire after image is fully displayed.