Rate Your Experience

How to Solve CSS Caching Issues With Cloudflare

Modified on: Sat, 25 Nov, 2023

What is Caching?

Caching refers to the short-term storage of files, such as images and web pages, so that the same files don't have to be loaded every time a page is viewed. This typically speeds up the experience for the user as it reduces the amount of data that has to be loaded. Caching can happen in a number of places. For example your web browser can cache files so it doesn't have to download all of the files all over again on a page you have visited before.  

A Content Delivery Network (CDN) such as Cloudflare will also cache files on a larger scale, so that after a file has been accessed on behalf of one user, the same file can be stored on their servers for other users too, without having to make additional requests to the origin server. By caching in this way, CDNs can reduce the time it takes to provide a cached file to the user.

Caching, CloudFlare, and CSS

One potential issue with caching is that it can lead to a situation where changes can be made to a site without that change being immediately visible to the site's visitors. This can happen whether the site has been cached by a web browser or by a server.

Although there are normally instructions in place to prevent caching from becoming problematic in this way, this can be a particular issue with cascading style sheets (CSS). If you're using CloudFlare with your site, they will cache your CSS for a long time. This means that if you make changes to your CSS, it will take a while before seeing them on the live site. 

CSS Caching Solution

This can be solved by altering the reference to your CSS file in the HTML for the given page so that a novel query string is added - for example altering "example.css" to "example.css?v=2.2.2". This typically causes both CDNs and web browsers to behave as though it's a new file that they haven't downloaded before - even if they have.

In the example given, CloudFlare will place on hold its usual assumption that "example.css" is the same file that it has always been using, and make a completely new request to the origin server to get the latest copy of the file. 

The origin server will ignore the query string "?v=2.2.2", but will nevertheless provide the latest version of the file. The next time "example.css" is updated, this can be changed to "example.css?v=2.2.3" - or to any number the publisher prefers - so that the CloudFlare will once again obtain the latest version.

More details about this strategy can be found here.

Loading ...