coiso February 2016

Lazy loading modules with angularjs and requirejs

I have been tackling this issue for a long time with great difficulty since there are a lot of articles that show how to load directives, services, and other angular components that use the word module to describe them.. ending up with an SEO nightmare.

All the solutions are incredibily complex, making dividing the JS files almost not relevant.

Has someone found a simple way to inject an angular module dependency to the main module when it's needed ?

Note: since I'm using require.js the actual JS is already present (also lazyloaded just when it's needed). So all that really is needed is to inject the modules onto angular.

Here is how close I got:

  1. window function in index.html to load the secondary .js file

    <script type="text/javascript">
        var hasBackLoaded = false;
    function loadBackOfficeJs (cb) {
        console.log("loadBackOfficeJs");
        if(!hasBackLoaded){
            var newScript = document.createElement('script');
            newScript.type = 'text/javascript';
            newScript.src = '<%=dist_cdn%>/scripts/back.js';
            newScript.onload = backLoaded;
            document.body.appendChild(newScript);
            function backLoaded(){
                console.log("back loaded")
                hasBackLoaded = true;
                cb();
            }
    
        } else {
            cb();
        }
    }
    

  2. call the previous function and try to load the angular modules into angular

    loadBackOfficeJs(function(){ require(['back'], function(){ //angular modules should be injected here.. somehow }); });

Answers


Melou February 2016

You should take a look at this lib ocLazyload

Most basic usecase is to load a module thanks to the provided $ocLazyLoad service.

$ocLazyLoad.load('yourModule.js');

This article was written by the lib's author when he started the library. Though it's a bit old now it's a good entry point to the internals of lazy loading modules.

Post Status

Asked in February 2016
Viewed 1,649 times
Voted 6
Answered 1 times

Search




Leave an answer