What's the simplest/modern way of caching partials in angularjs production?
Currently the code looks like:
$routeProvider.when('/error', {templateUrl: 'partials/error.html', controller: 'ErrorCtrl'});
Where the templateUrl is obviously an http path to a separate file. On mobile the loading time for that file is noticeable and I'd love to just cache everything.
The main part of the answer is the $templateCache. An extract:
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
Any of the html templates, can be moved to the $templateCache
, and the rest of our application will act as expected (no other changes required)
In case, that we would like to keep the template on the client, we can use the local storage as well. This angular-local-storage extension would simplify lot of stuff.
So, let's adjust the run()
to
local-storage
, if we do not already have the template on the clientlocal-storage
and $templateCache
)The adjusted code
.run([ 'localStorageService','$templateCache','$http',
function myAppConfig(localStorageService , $templateCache , $http) {
// The clearAll() should be called if we need clear the local storage
// the best is by checking the previously stored value, e.g. version constant
// localStorageService.clearAll();
var templateKey = "TheRealPathToTheTemplate.tpl.html";
// is it already loaded?
var template = localStorageService.get(templateKey);
// load the template and cache it
if (!template) {
$http.get(templateKey)
.then(function(response) {
// template loaded from the server
template = response.data;
localStorageService.add(templateKey, template);
$templateCache.put(templateKey, template);
});
} else {
// inject the template
$templateCache.put(templateKey, template);
}
}])
So, this way, we do profit from the local-storage
. It is filled with the "template" from the server, kept there... and therefore not loaded next time.
NOTE: Very important is also to inject some version
key/value and check it. If the Local storage is out-dated... all templates must be reloaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With