ed209
ed209

Reputation: 11293

How to force browser to refresh just one image after .attr('src', url) change?

I have an ajax upload script that returns an image that should swap out an exiting loaded image in the dom.

For example

<img src="http://site.com/user1-profile-pic.jpg" id="profile" />

and uploading a new image returns json

{"url": "http://site.com/user1-profile-pic.jpg" }

I then run jQuery

$("#profile").attr('src', myjson.url);

but the image url is always the same, so I want to bust the cache for that image to load it again. Could it be as simple as appending ?timestamp onto the end of the image URL?

Upvotes: 2

Views: 1870

Answers (1)

balexandre
balexandre

Reputation: 75103

it's the same because it's cached as you are using the same name, the trick is to use a different name.

As you can't use a different name, we append something to it:

var dt = new Date(); 
$("#profile").attr( 'src', myjson.url + '?dt=' + dt.getTime() );

in just one call (as Sushil says):

$("#profile").attr( 'src', myjson.url + '?dt=' + (+new Date()) );

this will output as:

enter image description here

Upvotes: 5

Related Questions