Prevent Annoying Template Caching in AngularJS 1.x

Hieu Pham
AngularJS tricks
Published in
2 min readJul 8, 2016

--

I had been struggling with the annoying template caching everytime we release new version of our AngularJS application, which is written in SPA manner. Our testers and customers always suffer the consequences of it.

AngularJS guys will understand.

- I don’t see that “new” button. Where is it?

- What are considered as new features over here? I don’t see anything different?

- I pressed F5 three times and nothing changed. What? I have to delete all the browser history data? Are you kidding me?…

(some other funny, angry, miserable stories keep adding…)

It looks like I’m not alone.

Finally my latest solution for this issue is writing a interceptor factory to add a query string to every template request, usually the url ended with ‘.html’ (but in my case, all the templates located in ‘views/*.html’).

...views/app.html?t=1467948997000

However, I’m not gonna use a regular timestamp as suggested in the last comment of the first StackOverflow post (by using new Date() function), but the timestamp of the latest Git commit because it keeps changing automatically during the development and stay the same once we deployed to production. You can use app version or whatever.

I use https://github.com/werk85/grunt-ng-constant to dynamically generate ENV constant and https://github.com/damkraw/grunt-gitinfo to collect all Git commit data

Here’s the code sample

'use strict';angular.module('preventTemplateCache')
.factory('preventTemplateCache', function($injector) {
var ENV = $injector.get('ENV');
return {
'request': function(config) {
if (config.url.indexOf('views') !== -1) {
config.url = config.url + '?t=' + ENV.build;
}
return config;
}
}
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('preventTemplateCache');
});

So far so good

Have you encountered such an issue?

--

--

Hieu Pham
AngularJS tricks

I'm a Frontend Engineer in Singapore. I might care about user experience more than your UX designer · https://hieugoesto.com