liquifiede liquifiede - 21 days ago 6
Javascript Question

Clear Angular JS templateCache once (for each deployment)

This issue AngularJS disable partial caching on dev machine suggests using

$templateCache.removeAll()
to clear the cache templates. However what if you just want to fire this once upon each deployment cycle in order to get visitor browsers to refresh/update the template? Our problem was some browsers were not updating the template html files, we'd end up with new CSS mixed with old HTML. I do not want this function to fire all the time, that would defeat the point of cache templates to begin with (right?).

Per the title question, what's a recommended way to clear $templateCache "once", for example some ideas I've crunched:


  • Does Angular have an internal method of detecting if the template file has changed? And then if so "update" it.

  • Does Angular have an internal "version" or "date" we could compare and add a conditional to fire function removeAll()?

  • Does $templateCache ever itself know to refresh? What were the Angular creator's intentions in forcing templateCache on us if HTML files are bound to change overtime and served to multiple browsers.



I do not want to use grunt to add workflow overhead for something that happens periodically, nor to chop up the html file templates into variables. (Is this a good method for template cache busting in angular?)

The alternative I can see is simply adding and removing removeAll() code manually, that would be silly.

Answer

We decided to go with simply tacking on UNIX timestamp version to files which were changed like file.php?v=154325232. The reason being we weren't actually using Angular templateCache, in that we weren't storing the template data itself inside templateCache. I thought Angular automatically stores any async loaded directive template files into templateCache, thats not true, you have to explicitly use templateCache to get a file (Good tutorial on that https://thinkster.io/templatecache-tutorial).

So our solution is just boring old versioning, which is most understandable by browser headers and for non-mega-scaling websites, just fine.

$modifiedTs = filemtime($filename);
if ($modifiedTs != $lastModificationTs){
  echo "$filename?v=" . time();
}

How to check if a file has changed?

Lastly the way I read templateCache, its not intended to save data between browser sessions rather its a cache service during the session. It has nothing to do with the browser cache, rather Angular stores it internally. So its meant for websites that dynamically navigate and load URLs (ie: not a true page refresh but an AJAX trick) which is how most of Google websites are today.

Comments