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) { }
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) { }
It'll load from cache if it's there, the same way a <img>
in your markup would.
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.
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://...';