Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 710
StevieB Avatar asked Nov 16 '16 22:11

StevieB


1 Answers

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

like image 154
Aravind Avatar answered Sep 22 '22 07:09

Aravind