javascriptbrowser-cache

Can I tell from javascript whether my page was hard refreshed?


I've given up on this, but I thought I'd post here out of curiosity.

What I call a "hard refresh" is the Ctrl+R or Shift+F5 that you do during development to see your changes.

This causes the browser to add a Cache-Control: max-age=0 header to the request and "child" requests like images and scripts, etc.

If you're doing your job, you'll get a 304 on everything but the resource that's changed. (Okay, well, see comments. This is assuming that other validators are sent based on browser caches.)

So far, so good.

The problem is that I'm not loading scripts directly from the page, but through a load.js, and the browsers are inconsistent about whether they include that Cache-Control header on those requests. Chrome doesn't do it at all, and Firefox seems to stop in the middle of a series.

Since I can't access the headers of the current request, there's no way to know whether that header should be included or not.

The result is that when I change a script (other than load.js), a hard refresh does not reliably work, and I have to, e.g., clear the browser cache (which is a bit heavy-handed).

Any thoughts on this?


Solution

  • Unfortunately you cannot detect a hard refresh from JavaScript (there is no access to the headers for the currently loaded page).

    However, the server can tell from the request headers if this is a hard refresh, so there's the option of cooperating. For example the server can include a custom <meta> tag in the response or add a special class to <body> and your script will then have access to this information.

    Once load.js detects a hard refresh it can then propagate it to the dependent scripts by e.g. attaching a URL parameter to the requests (think "?t=" + timestamp).