Lazy-load external JavaScript in one of AngularJS controllers

Some of my routes require functionality from external JS. I don’t want to download them all at once, since these JSs are needed only on certain routes (for example, /upload needs some JS for uploading photos, /photos needs another JS for lightboxes, /funny needs JS for animation, etc.) .

What is the best practice for lazily loading these external Java scripts?

These routes can be accessed several times (for example, the user can go to /upload , then /photos , then /upload again)

+8
angularjs
source share
3 answers

The only way I know to handle such cases is to use the route resolution method. This method can be used to determine the dependencies that must be loaded before an instance of the route controller is created. One of the various possible return types of this method is a promise. So you can use this to asynchronously load external JavaScript code and return a promise that resolves as soon as your external scripts are loaded.

Documentation on this subject can be found here: https://docs.angularjs.org/api/ngRoute/provider/$routeProvider in the "when" section.

+2
source share

In addition to what Alex said, if you are lazy loading AngularJS artifacts, such as controllers and directives, you will have to use the appropriate provider to register them instead of the module API. Artifacts registered using the module API after the application has been downloaded will not be available for the application. For example, you would define a lazy controller like this ...

 $controllerProvider.register('SomeLazyController', function($scope) { $scope.key = '...'; }); 

instead of this...

 angular.module('app').controller('SomeLazyController', function($scope) { $scope.key = '...'; }); 

I wrote a blog post detailing this, as well as how to use the solution method Alex talks about to implement lazy loading in AngularJS. http://ify.io/lazy-loading-in-angularjs/

+3
source share

@ alex3683 The answer is probably the correct AngularJS method, but I don't understand the concept, so I use jQuery getScript() instead. So, in CoffeeScript:

 yourModule.factory 'foo', -> $.getScript 'https://script-to-load', -> # whatever you want to do once the script is loaded 

And just call him from your controller. Since AngularJS services are lazy and single-user, this will only load the script once.

+2
source share

All Articles