Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is My Page Being Loaded from the Browser Cache?

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?

like image 601
Blackcoat Avatar asked Dec 13 '10 21:12

Blackcoat


People also ask

What happens when clearing browser cache?

When you use a browser, like Chrome, it saves some information from websites in its cache and cookies. Clearing them fixes certain problems, like loading or formatting issues on sites.

How do I stop a page from loading cache?

Here's how... When you're in Google Chrome, click on View, then select Developer, then Developer Tools. Alternatively, you can right click on a page in Chrome, then click Inspect. Click on the Network tab, then check the box to Disable cache.

What happens when a website is cached?

A site cache, also known as an HTTP or page cache, is a system that temporarily stores data such as web pages, images, and similar media content when a web page is loaded for the first time. It remembers the content and is able to quickly load the content each time the web page is visited again.


2 Answers

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
 }
like image 63
Matt Whittingham Avatar answered Oct 19 '22 20:10

Matt Whittingham


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.

like image 45
Jacob Avatar answered Oct 19 '22 20:10

Jacob