Is My Page Being Loaded from the Browser Cache?

2019-01-14 22:32发布

问题:

I have a "new items" badge on a page that I want to update immediately the page is loaded from the cache (i.e. when hitting "Back" or "Forward" to return to this page). What is the best way to accomplish this?

The setup is pretty simple. The layout for the app looks for new items every 8 seconds, and updates the badge + list of items accordingly.

$(function() {
    setInterval( App.pollForNewItems, 8000 );
});

When someone navigates away from this page to look at the details of an item, a lot can happen. Things are "new" until any user has viewed them, and the app will likely have several user using it simultaneously (the kind of workflow used for a call center or support tickets).

To make sure that the badges are always up to date, I have:

$(window).bind('focus load', function ( event ) {
    App.pollForNewItems();
});

..And though this works, polling for new items on 'load' is only useful when the page is loaded from the cache. Is there a reliable cross-browser way to tell if a page is being loaded from the cache?

回答1:

A partial hacky solution is to have a var with the current time set on the server, and set a var with the current client time at the top of the page. If they differ by more than a certain threshold (1 minute?) then you could assume it's a cached page load.

Example JS (using ASP.Net syntax for the server side):

var serverTime = new Date('<%= DateTime.Now.ToUniversalTime().ToString() %>');
var pageStartTime = Date.UTC(new Date());
var isCached = serverTime < pageStartTime &&
               pageStartTime.getTime() - serverTime.getTime() > 60000;

Alternatively, using cookies on the client side (assuming cookies are enabled), you can check for a cookie with a unique key for the current version of the page. If none exists, you write a cookie for it, and on any other page access, the existence of the cookie shows you that it's being loaded from the cache.

E.g. (assumes some cookie helper functions are available)

var uniqueKey = '<%= SomeUniqueValueGenerator() %>';
var currentCookie = getCookie(uniqueKey);
var isCached = currentCookie !== null;
setCookie(uniqueKey); //cookies should be set to expire 
                      //in some reasonable timeframe


回答2:

Navigation Timing is in most browsers now(ie9+) http://www.w3.org/TR/navigation-timing/#sec-navigation-info-interface

 if (!!window.performance && window.performance.navigation.type === 2) {
   // page has been hit using back or forward buttons
 } else {
   // regular page hit
 }


回答3:

You can ask the web browser to not cache the page. Try these HTTP headers:

Cache-control: no-cache
Cache-control: no-store
Pragma: no-cache
Expires: 0

Particularly, Cache-control: no-store is interesting because it tells the browser to not store the page in memory at all which prevents a stale page being loaded when you hit the back/forward button.

If you do this instead, you don't have to poll for data on page load.



回答4:

Personally, I would set data attribute containing the item id for each element.

I.e.

<ul>
  <li data-item-id="123">Some item.</li>
  <li data-item-id="122">Some other item.</li>
  <li data-item-id="121">Another one..</li>
</ul>

Your App.pollForNewItems function would grab the data-item-id attribute of the first element (if newest are first) and send it to the server with your original request.

The server would then only return the items WHERE id > ... which you can then prepend them to the list.

I'm still confused as to why you want to know if the browser has a cached version of the page.

Also, is there a reason for binding to load instead of ready?

  • Christian


回答5:

good answer: https://stackoverflow.com/a/9870920/466363

You could also use Navigation Timing to measure the network latency in great detail.

Here is a good article: http://www.html5rocks.com/en/tutorials/webperformance/basics/

If the time difference between fetchStart and responseStart is very low, the page was loaded from cache, for example.

by stewe