3

Look at the following code. Chrome logs one request in debug console. If this is because of caching, why does it not log two requests with the last one being 304?

What explains this browser behavior?

<script>
     new Image().src="//stackoverflow.com/"
     new Image().src="//stackoverflow.com/"
</script>
Salman A
  • 262,204
  • 82
  • 430
  • 521
sinbar
  • 933
  • 2
  • 7
  • 25
  • 1
    This is not a 304 answer. Chrome displays 304 requests. i think that chrome caches the first request and the second is a cache hit. – wartoshika Aug 16 '17 at 09:51
  • If you want to encourage multiple requests, add different _GET_ parameters to the URL – Paul S. Aug 16 '17 at 10:32

2 Answers2

6

The browser has already downloaded the image, why would it make another request for the same image? If an image is used more than once on a page (which happens regularly), making an individual request for each instance it's used would produce a ton of unnecessary overhead. Two images with the same URL within the same page are assumed to be the same image.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 2
    This effect is particularly visible with GIF animations, where images with the same filename will stay in sync even if loaded at intervals. I made a demo in response to some other question a while ago: http://adamhaskell.net/misc/numbers/numbers.html – Niet the Dark Absol Aug 16 '17 at 09:55
2

You are requesting the same image twice. The behavior is actually described in HTML5 specifications. Quote:

If the resource is identified by an absolute URL, and the resource is to be obtained using an idempotent action (such as an HTTP GET or equivalent), and it is already being downloaded for other reasons (e.g. another invocation of this algorithm), and this request would be identical to the previous one (e.g. same Accept and Origin headers), and the user agent is configured such that it is to reuse the data from the existing download instead of initiating a new one, then use the results of the existing download instead of starting a new one.

HTML5 > Common infrastructure > Fetching resources > Processing model

Basically it says that if you request the exact same resource multiple times, the browser downloads it only once (or not download it at all and serve from cache instead).

Relevant specs in reverse order:

Salman A
  • 262,204
  • 82
  • 430
  • 521