AngularJS Delayed Load html template

  • 2021-07-06 09:53:17
  • OfStack

When using routes/views mode in AngularJs to build a large website or application, it is not a good way to load all custom files, such as controllers and template, when initializing. The best way is to load only the required files during initialization. These files may depend on one connection or multiple files, but they are only used by a specific route. When we switch route, files that are not loaded will be loaded on demand. This can not only improve the speed of initializing pages, but also prevent bandwidth waste.

Most articles on the Internet talk about the delayed loading of controller through $routeProvider and third-party services, for example, Controller, which loads AngularJS on demand, explains it in great detail. However, there are few articles about the delayed loading of controller, html/template with $stateProvider. Although I looked at a lot of source code related to $stateProvider, although I solved the delayed loading problem of html/template, I still didn't solve the delayed loading problem of controller, which is a pity. Due to the time problem, the investigation results will be sorted out first, and the investigation will continue later.

For the delayed loading of html/template, the html file needs to be placed in a different directory from the home page file, otherwise it will be loaded automatically. Likewise, you cannot specify a file with templateUrl, otherwise it will be loaded automatically. The template attribute of $stateProvider. state supports string values and functions, so one function can be defined to load and cache html files to prevent duplicate loading of files. Want controller to do the same treatment, but unfortunately not find controller function definition, try many methods are invalid, and so on later study the source code to see what is missing. Directly on the code, logic is not complicated, not much wordy.


//  Record loaded html As well as controller Prevent duplicate network loading 
$ionic.files = {html: {}, controller: {}};
//  Declare delayed loading html Method 
$ionic.getHtml = function getHtml(name) {
if (!$ionic.files.html[name]) {
//  Synchronization ajax Request loading html And cache 
$ionic.files.html[name] = jQuery.ajax({url: 'views/' + name + ".html", async: false}).responseText;
}
return $ionic.files.html[name];
}
//  Declare delayed loading js Method  function resolveController(name) {
// var fn = $.getScript('assets/controller/' + name + '.js');
jQuery.ajax({"url": 'assets/controller/' + name + '.js', "dataType": "script", "async": false});
// console.log("load " + name);
return name;
} 
$stateProvider.state('login', {
url : "/login",
controller : resolveController("loginController"), 
template : function() { return $ionic.getHtml("login"); }
});

Related articles: