Detecting if a page is cached

Detecting on the client side whether a page was served from Cache can be an important feature for your website. You don’t want folks reading stale news if you’re updating it frequently, your article might have had a refresh, you might be serving up live content that is static. I feel this will mainly occur when using service workers, where the page in cache is always returned before going to the network. This tutorial from Jeremy shows how we can timestamp our pages and then run some clientside JS to detect if it’s a recent version.

Jeremy Keith - Adactio site screenshot

In my case, pages are generated by PHP. I’m not doing a database lookup every time you request a page—I’ve got a server-side cache of posts, for example—but there is a little bit of assembly done for every request: get the header from here; get the main content from over there; get the footer; put them all together into a single page and serve that up.

This means I can add a timestamp to the page (using PHP). I can mark the moment that it was served up. Then I can use JavaScript on the client side to compare that timestamp to the current time.

An excerpt from Detecting if a page is cached

View original article

Subscribe to our Newsletter

Add your email address and receive an email every Friday covering off everything worth knowing about building your websites responsively.