Today I Learned - Rocky Kev

TIL HTTP "No-cache" headers

POSTED ON:

TAGS:

I was working on a very old PHP project that was getting some weird caching issue on some client's browser.

Running out of ideas, I decided to go server-side.

<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP 1.1
header("Pragma: no-cache"); // HTTP 1.0
header("Expires: Wed, 1 Jan 2020 00:00:00 GMT"); // Anytime in the past

// REST OF THE PAGE AS USUAL ?>

<!DOCTYPE html>

This page is now set to “no-cache, always reload”. This will most likely cause the browser to reload everything on the page itself. For the sake of performance, you might want to turn off these headers after some time, after most of the users have gotten the updated page.

via Force Reload Javascript CSS In Browsers (Simple Examples)

This is a good idea for a single page. But sucks with a lot of pages.

Instead, you want to go to even higher. Into their Apache it is!

Just add a small snippet in the .htaccess file.

<IfModule mod_expires.c>
  ExpiresActive on
  ExpiresByType text/css "access"
  ExpiresByType text/js "access"
  ExpiresByType text/javascript "access"
</IfModule>

That will pretty much expire all CSS and Javascript files the moment users access them, and encourage browsers to reload them. I will somewhat recommend this method if you roll out updates on a regular basis, mass controls using this Apache module is much more flexible and powerful.


Related TILs

Tagged:

TIL Clear-Site-Data

The Clear-Site-Data header clears browsing data (cookies, storage, cache) associated with the requesting website. It allows web developers to have more control over the data stored by a client browser for their origins.

TIL loading third-party scripts onto service workers

An alternative to self-hosting scripts would be using Service Workers to cache them. This can give you greater control over how often they are re-fetched from the network. This could also be used to create a loading strategy where requests for non-essential third parties are throttled until the page reaches a key user moment.

TIL HTTP "No-cache" headers

Using PHP and apache .htaccess file to force reload