4

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) { }
2
  • I would setup the onload prior though. IIRC there are some strange Opera quirks with at least onerror and posting events synchronously vs. async. My memory fails though. Commented Oct 19, 2010 at 19:31
  • If you don't want to have it cached, add some random parameters to the source value, like: 'image.jpg?random=' + new Date().getTime() Commented Oct 19, 2010 at 19:31

3 Answers 3

8

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://...';
Sign up to request clarification or add additional context in comments.

Comments

7

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

2 Comments

(Or perhaps not load from cache-- those pesky misconfigured servers!)
Well, he is close to century of bronze medals.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.