eb80
eb80

Reputation: 4738

Preload AngularJS partials used in routes?

Question: What is the best way and the best time to pre-load .ng files that are used in routing templates?

In researching this thus far, I've found the following answers:

  1. Use Angular's script directive. Problem: My content cannot be loaded as a literal string but needs to be fetched from the server. In other words, I have an .ng file as my partial so I cannot do

    my content must remain in a .ng file on the server and be fetched
  2. Use $templateCache.put to put a template literal in the cache. Same problem as above.

  3. Use $http to load the .ng file. This works in that it is not a string literal but I am struggling to find the best time to perform this so that it is not blocking (realize its async but still)

To save you from suggesting resources I've already seen, I've read the following: Is there a way to make AngularJS load partials in the beginning and not at when needed?

https://groups.google.com/forum/#!topic/angular/6aW6gWlsCjU

https://groups.google.com/forum/#!topic/angular/okG3LFcLkd0

https://medium.com/p/f8ae57e2cec3

http://comments.gmane.org/gmane.comp.lang.javascript.angularjs/15975

Upvotes: 1

Views: 1065

Answers (1)

Joe
Joe

Reputation: 2596

Maybe use a combination of 2 and 3.

Like you said, $http is async, so why not just put each partial into the templateCache after the app has loaded.

For example:

var myApp = angular.module('myApp', []);
myApp.run(function($http, $templateCache) {
  var templates = ['template1.ng', 'template2.ng'];

  angular.forEach(templates, function(templateUrl) {
    $http({method: 'GET', url: templateUrl}).success(function(data) {
      $templateCache.put(templateUrl, data);
    });
  });
});

I've never had the need for this and definitely haven't tested it, but the idea is there.

Upvotes: 1

Related Questions