Using XHR to secure resources that do not meet expectations

I'm just trying to use XHR to protect some resources, but the cache isn't behaving as expected.

Here are the estimates of the problem:

  • I know the resource url in advance (of course).
  • I don't know their content types (mix of CSS, images, etc.).
  • They will always be of the same origin.
  • I am managing cache headers.
  • They can be cached forever for whatever I need.

I always got the impression that XHR used the browser cache more or less like any other resource, but never tested this rigorously. That's what I'm doing:

  • Request all resources with XHR.
  • Set the request header explicitly Cache-Control: max-age=3600

    (Chrome installed for some reason max-age=0

    ).
  • Set the following response servers on the server:

    • Cache-control: public; max-age=3600

    • Date: now

    • Expires: now + 1 hour

    • [Content-Type, Content-Length]

This is what I see:

  • XHR always selects a resource (confirmed on the server and with dev tools).
  • Subsequent requests (via image / css / etc elements) always fetch (even after the XHR is complete) into the cold cache.
  • But they always use the cache when it heats up.

I poked it in different ways, but this behavior never changes.

+3


source to share


1 answer


After a lot of yelling and gnashing of teeth, I believe I have proven that this approach simply won't work on all browsers. Here's my experience:

  • Firefox : works lovely.
  • Chrome : Rarely works - as if XHR uses a different cache than elements (although I'm pretty sure it doesn't, I didn't have time to dig deeper into the Chrome code to figure out exactly what was going on.
  • Safari : Apparently random. Sometimes resource requests started with items fetched from the cache, sometimes not. I'm sure there is a method, but it seems crazy from the outside.


In the end, I had to switch to a slightly more flawless but reliable approach to creating a hidden iframe by injecting script / img elements into it and then waiting for the onload iframe event. This works, but does not provide the subtle feedback in which the elements are loaded (receiving reliable onload events from individual elements is more "cross-browser" than just waiting on the whole frame.

I would like to understand more precisely what is going on in Chrome / Safari, but unfortunately you don't have time to dig further.

0


source







All Articles