Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cache angularjs partials?

Tags:

angularjs

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.

like image 486
MB. Avatar asked Mar 21 '23 21:03

MB.


1 Answers

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)

local-storage as a cache

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

  1. observe the local-storage, if we do not already have the template on the client
  2. issue the request to load the latest, if needed...
  3. put it into the caches (local-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.

like image 131
Radim Köhler Avatar answered Mar 31 '23 22:03

Radim Köhler