简体   繁体   中英

AngularJS: what is $templateCache?

While profiling a large AngularJS app, I started tracking $templateCache.

https://docs.angularjs.org/api/ng/service/ $templateCache

What is this object? Does it store the partials as they are stored on disk or the final rendered HTML from the route?

I've added some code like this to my controller to make sure it's not persisting anything:

$scope.$on('$destroy', function cleanup() { $templateCache.removeAll(); });

EDIT : the reason I am looking into this is that a single (not every) controller is loading a large partial with several loops inside of it, depending on User input it could be about 100 input fields with large <select> statements and many custom directives. The client is requesting it be this way and I want to make sure that all of this is getting disposed during routing.

To clarify the question: $templateCache is only storing the partials as they appear on disk, no routing or rendering information is being stored?

By default, while loading templates, Angular looks inside $templateCache and fetches templates over XHR when it cannot find them locally in its $templateCache. When the XHR request is slow or our template is large enough, it can seriously negatively impact end users' experience . instead of fetching templates XHR, we can fake the template cache loading by wrapping it into a JavaScript file and shipp the JavaScript file along with the rest of the application.

Sample :

angular.module('myApp')
.run(['$templateCache', function($templateCache) {
$templateCache.put('xyz.html', ...);
}]);

So, unless you are very much sure to remove the cached templates form $templateCache, don't do that.

If I remember correctly, it's a object where partials are saved. When making a request to any html file (through routing, directives or include) , angular first looks into $templateCache , and if required file doesn't exist, it will make a request for it and will put it in the cache. But if it does exists, it is taken from there. So if you are using your directive 100 times per page, it will only make one request for your directive file, or if you navigate back and forth your app, it won't request files that were already loaded.

Does it make sense to add $templateCache.removeAll(); on each controller? Only if it's really small application, otherwise I suggest not messing around with it..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM