javascriptangularjsangularjs-templates

How to force a browser to reload angular template file and not cache it?


When loading a javascript file I can force the browser to not use the cache by adding a version when loading the file e.g.

<script src="~/angular/myapp/app.js?version=123"></script>

From inside my angular app I am doing this:

$routeProvider.when("/", {
  controller: "userController",
  controllerAs: "vm",
  templateUrl: "Path/to/Template/Index.html"
});

How can I make sure that any changes I made to the Index.html won't be cached? Or this isn't an issue for some reason?

angular 1.x


Solution

  • You could do the same for your Index.html file. Simply append a "cache buster" query string as you did to your js file. There are a few techniques to do this, but a simple Date.now() timestamp should demonstrate the goal ...

    $routeProvider.when('/', {
      controller: 'userController',
      controllerAs: 'vm',
      templateUrl: `Path/to/Template/Index.html?t=${Date.now()}`
    });
    

    If your app grows in complexity and you wish to prevent caching of templates altogether, you can achieve this with some middleware...

    angular.module('preventTemplateCache').factory('preventTemplateCache', function($injector) {
      return {
        'request': function(config) {
          if (config.url.indexOf('views') !== -1) {
            config.url = `${config.url}?t=${Date.now()}`
          }
          return config;
        }
      }
    }).config(function($httpProvider) {
      $httpProvider.interceptors.push('preventTemplateCache');
    });
    

    The above example assumes a directory of views for your templates.


    Finally, as a comment pointed out, if you are simply wishing to prevent caching for local development, you can toggle settings to disable cached resources through your browsers dev tools.