Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache busting with Scripts.Render but without bundle URL

When using Bundles with EnableOptimisations set to true, the output URL contains a hash to prevent the browser from loading the file from cache if it has changed.

@Scripts.Render("~/content/js/global")

Outputs:

<script src="/content/js/global?v=PqstRRGF8qsUsJfHu6NBBBp6eDxYBz1JCbHY6CQJVks3"></script>

However, some files in our application are specific to one page. We reference these directly:

@Scripts.Render("~/areas/areaname/content/js/page-name.js")

The output URL in this case does not have the hash and is therefore cached, causing problems when we release changes to these files.

We rather not change every reference individually or have to manually change the URLs every time we change the files.

How can I globally add a hash (or a version number) to all script and style URLs that are not bundles?

like image 419
Connell Avatar asked Feb 16 '16 15:02

Connell


1 Answers

I ended up with an entirely different solution, however, I have stumbled across a question containing an idea that would've helped me and hope this helps others.

You can manually set the default tag formats and include the version number.

string versionNumber = "1.2.3.4"; // get from assembly or config setting

Styles.DefaultTagFormat = string.Format("<link href='{{0}}?v={0}' rel='stylesheet'/>", versionNumber);
Scripts.DefaultTagFormat = string.Format("<script src='{{0}}?v={0}'></script>", versionNumber);

Only issue I can see with this is if your URL already contains a querystring. This would append a second ? rather than an &.

like image 199
Connell Avatar answered Sep 19 '22 00:09

Connell