Cache busting JavaScript files using webpack and ASP.NET

Neil Kennedy
the-stepstone-group-tech-blog
3 min readJun 15, 2020

--

Anyone who has released a website into production knows about cache busting. The last thing you want to happen is to release a new version of your website and see a long list of errors in your logs because people are still using the previous version of your JavaScript files.

Luckily if you’re using webpack there’s an easy way to append a unique id to your bundled files to bust the cache. The hard part is figuring out how to include those dynamic filenames into script tags in your ASP.NET razor files.

Cache busting with webpack

The most straightforward way to generate cache busting filenames is to use the [contenthash] substitution parameter in your webpack config.

This will create a filename that looks something like

myapp.395c014a2ec0b3282eb7.js

This file will need to be included in the script tag in your .cshtml file but the filename will change whenever the content of your file changes and we don’t want to manually update the script tag each time.

ASP.NET Core

Thankfully, ASP.NET Core comes with a built-in way to include dynamic JavaScript filenames.

TagHelpers were introduced a few years back and provide additional functionality to regular html elements by running transformations on the server before sending the response to the client.

The script tag includes an additional attribute called “asp-src-include” that allows us to provide a wildcard character to link our dynamic filename. If you view the source in your browser, you will see the dynamic filename has been substituted in the src attribute.

ASP.NET

Unfortunately, ASP.NET in .NET Framework does not come with the script tag helper built in, but we can recreate something similar with html helpers.

The below code will look in our dist folder and use a regex to match our filename and return the correct file every time, even when the hash changes.

And then in your .cshtml file you can add the following

This will do the same as the ASP.NET Core script above. If you check your browser, you’ll see the correct dynamic filename has been substituted in the src attribute.

Use a static filename for local development

It’s not ideal to have your filenames constantly changing when you’re working locally so a nice hack is to utilise a “development” switch in your webpack config. Webpack has a “mode” property that most people should be setting to “development” or “production” depending on when you build your app. For a development build you can use the below config which will give you a consistent filename and still work with the razor helpers above.

Read more about the technologies we use or take an inside look at our organisation & processes. Interested in working at StepStone? Check out our careers page.

--

--

Neil Kennedy
the-stepstone-group-tech-blog

Solution Architect based in London. Loves building products.