Have you ever met browser caching issues that you have to ask your users to use Ctrl + F5 to fix the problem? Do you want to get rid of this user-unfriendly behavior?

There are many ways to prevent this issue from happening. I just mention the promising three here [3].

  • File name versioning (e.g. style.v2.css).
  • File path versioning (e.g. /v2/style.css)
  • Query strings (e.g. style.css?ver=2). It is probably adequate because Stackoverflow currently uses this technique, and there are millions of Stackoverflow users [1]. But some authors point out it doesn’t always work [4]

File name versioning and file path versions, by theory, will always work.

Our life can become much easier if we just let the framework to do the job.

If you use asp.net MVC 5, you are lucky because it’s built in with bundling feature. In addition, the bundle path points to a virtual path, and makes it easy to change this virtual path.

public static void RegisterBundles(BundleCollection bundles)
{
    string version = "{version}"; // version from app settings, etc
    bundles.Add(new ScriptBundle("~/bundles/ABC-" + version)
           .Include("~/Scripts/ABC1.js",
                    "~/Scripts/ABC2.js",
                    "~/Scripts/ABC3.js"));

    // Code removed for clarity.
    BundleTable.EnableOptimizations = true;
}

For how to use MVC 5 bundling feature in details, please refer to Bundling and Minification [9].

Background: I talked to Mike, a front-end expert. He mentioned there was a term for fighting these unwanted browser caching behavior, and the term is call “Cache Busting”. I used to search using the keywords such as “clean browser caches”. Now I can search by “cache busting” instead.

By the way, the approach of cleaning browser caches programmatically using Javascript is a dead-end road because of security concerns that browsers will never allow you to do so. [6]

References:

  1. https://stackoverflow.com/questions/9692665/cache-busting-via-params
  2. http://www.adopsinsider.com/ad-ops-basics/what-is-a-cache-buster-and-how-does-it-work/
  3. https://www.keycdn.com/support/what-is-cache-busting/
  4. https://css-tricks.com/strategies-for-cache-busting-css/
  5. https://stackoverflow.com/questions/8155064/how-to-programmatically-empty-browser-cache
  6. https://www.quora.com/Is-there-a-method-to-program-an-automatic-clearing-of-a-browser-cache-in-JavaScript
  7. https://www.aspsnippets.com/Articles/Using-Bundles-ScriptBundle-in-ASPNet-MVC-Razor.aspx
  8. https://stackoverflow.com/questions/11979718/how-can-i-specify-an-explicit-scriptbundle-include-order
  9. https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification
  10. http://www.tutorialsteacher.com/mvc/scriptbundle-mvc
  11. http://www.c-sharpcorner.com/article/bundling-in-asp-net-mvc-application/
Advertisements