On this page
Angular logo and text "cache busting assets" next to it

Cache busting in Angular for static assets

Learn how to cache-bust static files in Angular by generating asset hashes during builds and adding them to URLs through a reusable pipe for reliable updates.

Images and other assets in your assets folder that you reference in Angular templates are not hashed by default, and we are going to solve that problem.

What is cache busting in Angular?

When building, Angular adds a hash to JavaScript, CSS, and assets directly referenced inside CSS files, but not to unreferenced static assets such as PDFs, images, and documents in your assets folder.

Cache busting is a technique that forces the browser to fetch the most recent version of a file rather than serving a cached copy. Because static browser cache policies can persist files for a long time, updating a static asset on the server without changing its filename often results in users seeing stale, cached content instead of the update.

Cache busting solves this issue by appending a unique file version identifier or adding a unique URL query parameter to the asset URL. This signals to the browser that a new version of the file exists, prompting an HTTP request to the origin server for the updated asset.

A solution to the cache busting problem in Angular

The solution is to inspect all static assets during the build process, compute their content hashes, and output the mapping to a single JSON file.

This is particularly useful when updating static assets under existing filenames while guaranteeing that browsers immediately receive the latest files.

Angular cache busting example result

Effortlessly manage and update static assets in your Angular application

While various approaches exist to handle asset caching, we can implement an automated build step and Pipe in the following way:

  1. Install the npm package @sitelintcode/angular-static-assets-hash.
  2. Run the CLI command npx createAngularStaticHashes.
  3. By default, the package scans for static assets in [angular root]/assets/images, but custom directories can be specified with --staticAssetsPath=[path to static assets].
  4. The package scans all files in the designated directory, customizable via --globPattern=[glob pattern] (default: /**/*).

The execution generates an assets.json file containing path-to-hash mappings for all processed assets.

Example output of assets.json
{
  "assets/images/example.png": "iY5RY0G8wePLPRkZSTgW2XYZFZ7kQOqXoJTFpQFG5nI",
  "assets/images/avatar.svg": "7A7qFs_iOghsdUtLG-7y-5cxT3FC8S_BRXl5ldsNY7Y",
  "assets/images/body-background.svg": "K2FTBtDsxgKLQFr4BUW1ptnLWqPCKPyGypHCBTfcctQ",
  "assets/images/icons.svg": "Ka-ngr7Fht6ucmN03kzJeMN7f2iOtnkD-D63QJ01jhM"
}

Angular-based approach for cache busting static assets

Once the asset index is generated, we can consume it dynamically inside Angular templates using an Angular Pipe.

Below is the implementation of the Pipe:

Pipe code that adds a hash parameter to the asset URL
import { Pipe, PipeTransform } from '@angular/core';
import staticAssetsList from '../../assets.json';

@Pipe({
  name: 'fileHash',
  pure: true,
  standalone: true
})
export class FileHashPipe implements PipeTransform {
  private readonly staticAssets: Record<string, string>;

  constructor() {
    this.staticAssets = staticAssetsList;
  }

  /**
   * Adds query parameters to a URL while preserving hash fragments
   */
  private addCacheParamToUrl(givenUrl: string, urlParameters: string): string {
    if (typeof urlParameters !== 'string') {
      throw new TypeError(`urlParameters must be a string, got ${typeof urlParameters}`);
    }

    if (urlParameters.trim() === '') {
      return givenUrl;
    }

    const hashIndex = givenUrl.indexOf('#');
    const urlWithoutHash = hashIndex === -1 ? givenUrl : givenUrl.substring(0, hashIndex);
    const hash = hashIndex === -1 ? '' : givenUrl.substring(hashIndex);

    const queryIndex = urlWithoutHash.indexOf('?');
    const baseUrl = queryIndex === -1 ? urlWithoutHash : urlWithoutHash.substring(0, queryIndex);
    const existingQuery = queryIndex === -1 ? '' : urlWithoutHash.substring(queryIndex + 1);

    const mergedParams = new URLSearchParams(existingQuery);
    const newParams = new URLSearchParams(urlParameters);

    newParams.forEach((value, key) => {
      mergedParams.set(key, value);
    });

    const queryString = mergedParams.toString();
    const result = queryString ? `${baseUrl}?${queryString}` : baseUrl;

    return hash ? `${result}${hash}` : result;
  }

  private getHashForStaticAsset(assetPath: string): string | null {
    const cleanPath = assetPath.split('?')[0].split('#')[0].replace(/^\//, '');
    return this.staticAssets[cleanPath] || null;
  }

  public transform(filePath: string): string {
    if (!filePath) {
      return filePath;
    }

    const hash = this.getHashForStaticAsset(filePath);

    if (!hash) {
      console.warn(`[FileHashPipe] No hash found for asset: ${filePath}`);
      return filePath;
    }

    return this.addCacheParamToUrl(filePath, `c=${hash}`);
  }
}

In Angular templates, the pipe can be applied using standard property binding syntax:

URL parameter with a hash for the image
<img [src]="'assets/images/example.png' | fileHash" alt="">

The rendered HTML output in the browser DOM will be:

URL parameter with a hash for the image
<img src="assets/images/example.png?c=iY5RY0G8wePLPRkZSTgW2XYZFZ7kQOqXoJTFpQFG5nI" alt="">

This hash technique is particularly effective for SVG symbol sprites (e.g., a single file containing all <svg> icons). Updating sprite icons automatically updates the query parameter while keeping template bindings clean and readable.

URL parameter with a hash for the SVG sprite
<svg aria-hidden="true" focusable="false" viewBox="0 0 48 48" width="32" height="32">
  <use [attr.href]="'assets/images/icons.svg#image-logo' | fileHash"></use>
</svg>

Share your feedback and improve the solution

This approach offers a reliable method for managing static asset cache busting in Angular applications. Community feedback and contributions are welcome.

Found an issue? Report it directly on the GitHub @sitelintcode/angular-static-assets-hash repository.

Explore a real-world example of cache busting in Angular

You can observe this implementation in action by exploring the SiteLint Platform, powered by Angular.

Related posts

Comments

Leave a Reply

Search in sitelint.com

Audit and debug pages with browser extension

Boost your website’s quality by auditing your page with SiteLint, a chromium-based extension that improves accessibility, quality, technical SEO, and provides easy-to-understand reports to help you prioritize and fix issues.