0

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 }); });

1

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm looking for a more direct approach since this library is quite heavy and complex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.