VB_
VB_

Reputation: 45692

Change img src not update the image

UPDATE

Finally got why it doesn't work. Server throw an error when I add timestamp attribute to avatar.src. I have a default no-avatar picture, but for some reason when you set incorrect src it just not updated.

I have the next image:

<img id="avatar" src="http://<my_host>/download?userId=1"/>

And after update it on the server I unsuccessfully try to update it on client:

const avatar = document.getElementById("avatar");
// PROBLEM: not update an image
avatar.src = avatar.src + '&timestamp=' + new Date().getTime(); 

BUT:

const avatar = document.getElementById("avatar");
debugger; // NOW REFRESH WORKS!!
avatar.src = avatar.src + '&timestamp=' + new Date().getTime(); 

Question: how to update the image?

Upvotes: 0

Views: 2917

Answers (1)

mplungjan
mplungjan

Reputation: 177688

Please note that const will not work in older browsers.

I would have guessed your usage of const fails to store the image object. Instead I suggest this:

var avatar = document.getElementById("avatar");
var src = avatar.src;
avatar.src = src + '&timestamp=' + new Date().getTime(); 

It does not make sense to store the image object in a const. Instead you could store the URL in a const:

const IMGURL = "http://<my_host>/download?userId=1";
var avatar = document.getElementById("avatar");
avatar.src = IMGURL + '&timestamp=' + new Date().getTime(); 

UPDATE: Since var does the same thing in OP's code, I would now look at timing issues. If the setInterval or whatever is used is too fast, adding debugger may slow it down to allow the loading. Hit F12 and see if the network tab shows a lot of interrupted calls

Upvotes: 4

Related Questions