1

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

Community
  • 1
  • 1
eb80
  • 4,700
  • 5
  • 25
  • 30

1 Answers1

1

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.

Joe
  • 2,596
  • 2
  • 14
  • 11
  • if you're going go to this route, "$http.get(templateUrl)" will work just as well since Angular will cache the XHR anyway and it won't load when you click on the link that triggers the routing change and template load. – eb80 Dec 27 '13 at 22:57
  • @eb80 I don't understand what you mean here. Do you mean $http request will not fire until you click something? – Daiwei Dec 28 '13 at 06:34
  • @Daiwei - no. I mean that we do not need the ".success..." bit since Angular already caches the response. the $http will fire before page load... I am saying all we need is $http.get(templateUrl) we do not need the ".success..." bit – eb80 Dec 28 '13 at 18:15