27 April 2024

Blazor, Cache-busting tip for my CSS files

Cache-busting is a technique used to ensure that the user accesses the latest version of your files, be they JavaScript, style sheets (CSS) or images. This technique is designed to avoid certain problems that arise when your application is updated and the browser cache comes into play. In effect, Cache-busting bypasses the caching of older versions of files by assigning them unique identifiers or modifying their URLs, thus ensuring that users always access the most recent versions, unaffected by versions previously saved in the browser cache.

It happens so often, doesn’t it? The frustration when you change something in the app and those changes aren’t immediately reflected, especially when it comes to styling or JavaScript functions! We’re used to doing a CTRL+F5 to refresh the page, but when it’s a deployment for a customer who’s not familiar with these technical subtleties, it can be a real headache.

Tip 1: Add a Query to the URL

I understand, it can be tedious having to manually add an alphanumeric string to the end of the URL to force the browser to load the latest version of the files. And frankly, most of the time, you end up forgetting to do it. Conclusion: forget it

HTML

Tip 2: Using a Javascript function

I’m not very good at JS, but by placing a JavaScript function at the bottom of the index.html page that will generate a random number and concatenate it with the URL of the files, we can ensure that the browser will load the latest version of the resources each time the page is called up. Although this method is simple to implement, it can be an effective way of getting around the cache problem. Conclusion: it works 🚸

JS

Tip 3: Via a variable in appsettings.json

This is a really elegant way of handling it. By using a variable like “BUILD_NUMBER” in your appsettings.json file and retrieving it via IConfiguration in your application, you can dynamically incorporate this value into the routing file such as Routes.razor (or App.Razor for versions prior to .NET 8). This allows you to control resource URLs from a centralized source, simplifying cache-busting management for your entire application.

JSON
C#

The advantage of the latter solution is that you can modify this variable during deployment via your CI/CD pipeline.

Tip 4 : Use AssemblyVersion with reflection

In use, it looks like this:

HTML

So in the .csproj file, even though we’re already using , we’re going to add here:

Plain Text

It’s an easy solution that I like

Leave a Reply