views:

27

answers:

3

If I use new Image() to load up an image in JavaScript, will it use a cached version if possible, or will it always load up a fresh copy?

var imgObj = new Image();
imgObj.src = 'http://...';
imgObj.onload = function (loadedImg) { }
+5  A: 

It'll load from cache if it's there, the same way a <img> in your markup would.

Nick Craver
(Or perhaps not load from cache-- those pesky misconfigured servers!)
pst
+1 you're close to 100k buddy :)
galambalazs
Well, he is close to century of bronze medals.
JavaGeek
A: 

You can force a reload by adding a bogus query string argument. If your statement assigning a URL to the src property of the image is

imgObj.src = 'http://www.mySite.com/images/anImage.png';

you could render it as

imgObj.src = 'http://www.mySite.com/images/anImage.png?foo=0';

Just understand that on subsequent loads it will still use the cached copy unless you change the query string argument.

Robusto
+1  A: 

One thing to note is that if you want onload to always happen (even when it's in cache) you should define onload before src.

var imgObj = new Image();
imgObj.onload = function (loadedImg) { }
imgObj.src = 'http://...';
galambalazs
Good point. Thanks for that.
Mr. Flibble