Search code examples
angularjswebpacklazy-loadingoclazyload

AngularJS- Dynamic Loading of script files using LazyLoad- Webpack


Right now in my index.html page I have links to two CDN files one being a JS and the other a CSS file.

i.e. in the the bottom of my body

https://somedomain.com/files/js/js.min.js

and in the head

https://somedomain.com/files/css/css.min.css

But right now they aren't needed on my homepage but just in one particular route. So I was looking into how I can lazy load these CDN resources when that routes gets hit i.e. /profile and only then ?

These aren't installed via bower or npm but just loaded via CDN url for example jquery. How in Angular 1 and Webpack can I lazy load that based on a route ?


Solution

  • Here you go.. It is made possible using oclazyload. Have a look at below code. A plunker linked below

    I have a module Called myApp as below

    angular.module('myApp', ['ui.router','oc.lazyLoad'])
        .config(function ($stateProvider, $locationProvider, $ocLazyLoadProvider) {
                $stateProvider
                    .state("home", {
                        url: "/home",
                        templateUrl: "Home.html",
                        controller: 'homeCtrl',
                        resolve: { 
                            loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                                return $ocLazyLoad.load('homeCtrl.js');
                            }]
                        }
                    })
                .state("profile", {
                    url:"/profile",
                    templateUrl: "profile.html",
                     resolve: {
                          loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                          return $ocLazyLoad.load('someModule.js');
                            }]
                        }
                })
    
        });
    

    I have another module called someApp as below

    (function () {
    var mynewapp=angular.module('someApp',['myApp']);
    
    mynewapp.config(function(){
    
      //your code to route from here! 
    
    });
          mynewapp.controller("profileCtrl", function ($scope) {
    
                console.log("reached profile controller");
            });
    
    })();
    

    I have a Live Plunker for your demo here