Prevent browser cache of angular templates

2019-06-17 02:42发布

I've been researching back and fourth on this issue, which is quite simple: Modern browsers (chrome/ FF) are caching stuff, html pages among others.
When you release a new version, angular GETs these templates. However since the browser serve a cache version of these pages and not the new updated version.

I've read about 2000 article on how to achieve this.. None of the "meta" tags worked for me.. (for instance: Using <meta> tags to turn off caching in all browsers?) The only thing that works is manually manage the versions of the file by adding some param value http://bla.com?random=39399339. However this is really annoying and extremely tough to maintain if "clear caching" is only sometimes needed (mainly between versions).

Is there any chance browsers does not provide a simple, controlled way to manually "clear cache". Either on server or client way?

P.S. Angular template makes it even tougher to manage.

2条回答
再贱就再见
2楼-- · 2019-06-17 03:00

i am using interceptors. if request includes exact chunk of url(path to templates) i set header "Cache-Control": "no-cache, must-revalidate"

$httpProvider.interceptors.push(function($q,ngToast) {

        return {
            request: function(config){
                if(config.url.includes('some_url_to_your_template')){
                    Object.assign(config.headers,{"Cache-Control": "no-cache, must-revalidate"});

                }

                return config;
            }
        }
})
查看更多
3楼-- · 2019-06-17 03:05

This is a question with so many answers, and it depends on your server, etc...

  • Normally HTML files are not cached
  • AngularJS caches templates after first calling them, using the $templateCache service (during application runtime)
  • You can use html2js with grunt or gulp to compile your templates in one JavaScript file
  • A lot of people don't rely on client caching, etags, etc... and add a version, hash, suffix and/or a prefix to static resources uri
查看更多
登录 后发表回答