Find out how to make cache busting static files (images, pdfs, pngs, etc.) for the Angular application.
Images and other assets you have in your assets folder that you reference in Angular templates are not hashed, and we are going to solve that problem.
What is cache busting in Angular?
Cache busting is a method that lets the browser load the most recent version of a file instead of one that has already been cached. A static file that has been cached can be kept for a very long time until it eventually expires. When you update a website with the same file name, then the browser will provide not your fresh file but what’s available in the browser cache, so the user won’t be able to notice the modifications.
Cache busting solves the browser caching issue by using a unique file version identifier or by adding a unique URL parameter to the asset URL to tell the browser that a new version of the file is available. Therefore, the browser doesn’t retrieve the old file from the cache but rather makes an HTTP request to the origin server for the new file.
The solution would be to search for static assets, create a list of them with their hashes, and save the list as a JSON file.
This is useful when you want to change the same static asset without changing the name and ensure that the browser will always fetch the latest version.
In general, there might be very different solutions to that problem, but we are going to solve it in the following way:
- Install npm package @sitelintcode/angular-static-assets-hash.
- We’ll use the CLI command
- By default, the package searches for static assets in the folder
[angular root]/assets/images, but you can set any location through the parameter
--staticAssetsPath=[path to static assets].
- The package gathers a list of all files from a given location, but you can change that by adding the parameter –
-globPattern=[glob pattern]. Default:
The final result is the list of all assets collected in a single file called
assets.json with a path and the file hash.
Once the list of static assets is created, we need to have a way to use it with Angular. For that purpose, we can use an Angular Pipe.
Here is an example of the Pipe code:
In Angular code, you can use it the following way:
The result of the above code will give:
The hash is quite useful when we want to manage, e.g., one file with all
<svg> icons. While you could change your single file with all
<svg> icons all the time, your code remains the same.
The approach is one possible way to handle static assets and their cache busting. Feedback is very welcome.
Founded issue? Report it directly on Github @sitelintcode/angular-static-assets-hash repository.
You can see the implementation by looking at the source code of our SiteLint Platform, managed by the Angular framework.