简体   繁体   中英

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, eg, clear the browser cache (which is a bit heavy-handed).

Any thoughts on this?

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 eg attaching a URL parameter to the requests (think "?t=" + timestamp ).

You could try checking localStorage. Set a localStorage variable and check it. If it's there, it's not a hard refresh, otherwise, it is a hard refresh.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM