0

Does this script cause the image to be cached by the browser?

var img = new Image();
img.src  = "http://www.nasa.gov/sites/default/themes/NASAPortal/images/nasa-logo.gif"

Or will it be actually downloaded/cached only when added to the the DOM?

I can't see it anywhere in the Chrome debugger but I might be missing something.

Thanks

chris
  • 605
  • 7
  • 26

1 Answers1

0

Assuming there are no http headers instructing the browser to avoid caching, the image will be cached as soon as it is successfully downloaded, no matter whether it was downloaded in a javascript object, put in the DOM with JS or part of the page's HTML. That part makes no difference.

In fact, you can even preload images (into the cache) with pure javascript like this: How do you cache an image in Javascript.

Community
  • 1
  • 1
jfriend00
  • 580,699
  • 78
  • 809
  • 825
  • Actually I would like to avoid caching (for a valid reason). Is it something that can be done in the code above, or anywhere else on the client side? – chris May 24 '14 at 06:04
  • @chris - You can break caching at any time by appending something like `?rand=193471029374` to the image URL where the number is randomly generated each time you request the image. This makes the URL different every time so even though the previous image downloads are in the cache, the browser treats this as a different URL so it is requested again from the server. Or, you can configure the server to tell the client NOT to cache the image with the appropriate HTTP headers. You cannot, from javascript, prohibit caching of an image. – jfriend00 May 24 '14 at 07:14
  • I posted a new question with a better explanation of the problem: http://stackoverflow.com/questions/23842463/replace-purge-remove-cached-image-not-refresh – chris May 24 '14 at 07:34