Load Dynamically JavaScript file in AngularJs with RequireJs

Load Dynamically JavaScript file in AngularJs with RequireJs . If you are creating larger scale apps, where you need to deal with separate defined controllers, services and directives in different files which are required to get loaded for performing some part of functions. So it would be best practice to load controllers or services JavaScript file dynamically when required instead of loading all bunch of file at single hit, which might result in increasing latency time of response of page. Well this could be easily achieved with the help of RequireJs, where we just need to set and call required files, while the rest RequireJs would worry to do the importing.

Load Dynamically JavaScript file in AngularJs with RequireJs
Load Dynamically JavaScript file in AngularJs with RequireJs

As at this moment, I am also new to AngularJs, so I need to searched for the solution, for how to load JavaScript file dynamically in AngularJs, all around the Google. And now I am up with the perfect and simplest solution. With the help of AngularAMD and requirejs, allows you to build AMD (asynchronous module definition) modules, within some minutes.

“angularAMD is an utility that facilitates the use of RequireJS in AngularJS applications supporting on-demand loading of 3rd party modules such as angular-ui.” – Marcos Lin

Example – Load Dynamically JavaScript file in AngularJs with RequireJs

Here is the sample and description to load modules Dynamically in AngularJs projects. Requirement:
angularAMD.js
require.js
angular-route.js

Lets take a simple converter application, which will facilitates conversion of temperature and length, where temperature controller and length controller modules is defined in separate files. Now our target is to load temperature or length controller file, when required.

Firstly create boot.js, which will be loaded initially, where we will define modules path, shim and dependency. Here is how boot.js looks like:

In boot.js:

require.config({
    baseUrl: "js",
    paths: {
        //defining the variables to the path of resepective js files present in the project foler.
        angular: "../lib/angular.min",      
        "angular-route": "../lib/angular-route.min",
        angularAMD: "../lib/angularAMD"
    },
    shim: {
        //as requirejs follows AMD, so shim confirms the loading of dependent file in sequence.
        //here angularAMD and angular-route is dependent on angular, so angular is loaded before the two
        angularAMD: ["angular"],
        "angular-route": ["angular"]
    },
    //deps will execute app.js
    deps: ["app"]
});

In app.js

define(["angularAMD", "angular-route"], function(angularAMD) {
    var app = angular.module("webapp", ["ngRoute"]);    
    app.config(function($routeProvider) {
        $routeProvider
        .when("/", angularAMD.route({
            templateUrl: "template/home.html",
            controller: "HomeCtrl",
            //if all controller javascript file is defined in boot.js file,
            //there is no need to define controllerUrl in any of the case.
            controllerUrl: "js/HomeCtrl.js"
        }))
        .when("/temperature", angularAMD.route({
            templateUrl: "template/View.html",
            controller: "TemperatureController",
            controllerUrl: "js/TemperatureCtrl.js"
        }))
        .when("/length", angularAMD.route({
            templateUrl: "template/View.html",
            controller: "LengthController",
            controllerUrl: "js/LengthCtrl.js"
        }))
        .otherwise({
            redirectTo: "/"
        })
    });

    //this will bootstrap the application. There is no need to define 'ng-app' in HTML file
    return angularAMD.bootstrap(app);
});

In index.html:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="css/style.css">
    <!-- data-main define the entry point for RequireJS configuration-->
    <script data-main="js/boot.js" src="lib/require.js"></script>
  </head>
  <body>
    <div ng-view></div>
  </body>
</html>

In View.html

<h1><a href="#/">Home</a></h1>

<div id="inputElem">{{fromUnit}} <input class="item item-input" type="number" placeholder="0" step="0.01" ng-model="data" ng-change="getValue(data)"></div>

<div id ="rowvalue" class="row" ng-repeat="(key,value) in result">
	<div id="colvalue" class="col-sm-6">{{key}} : {{value}}</div>
</div>

In HomeCtrl.js

define(["app"],function(app){
	app.controller("HomeCtrl",function($scope){
		console.log("home controller is loaded");
})
});

In TemperatureCtrl.js

define(["app"],function(app){
    app.controller('TemperatureController', function($scope) {	
    	$scope.fromUnit = "CELSIUS";
		$scope.result = {'CELSIUS': '0', 'KELVIN':'0', 'FAHRENHEIT' : '0'};
		
                  $scope.getValue = function(temp){
			Fahrenheit = (temp * 9 / 5) + 32;
			Kelvin = temp*1.0 + 273.15;
			Celsius = temp;
			$scope.result = {'CELSIUS':Celsius, 'KELVIN':Kelvin, 'FAHRENHEIT' : Fahrenheit};
		};
	})
});

In LengthCtrl.js

define(["app"],function(app){
    app.controller('LengthController', function($scope) {	
    	$scope.fromUnit = "CENTIMETER";
		$scope.result = {'CENTIMETER':'0', 'METER':'0','INCH':'0'};
		 
                 $scope.getValue = function(temp){
			var cm = temp;
			var m = 0.01 * temp;
			var inch = 0.393700787401575 * temp; 
			$scope.result = {'CENTIMETER':cm, 'METER':m,'INCH':inch};
		};
	})
});

Here is the working demo of the above given code:

Demo : Load Dynamically JavaScript file in AngularJs with RequireJs

If you want to test for dynamically loading of JavaScript, open up Network tab of your browser and see how files get loaded when the page is called. If you are getting any difficulty, do comment below, we would try to resolve it. Also do share if you have another solution for the same.

One thought on “Load Dynamically JavaScript file in AngularJs with RequireJs”

Leave a Reply

Your email address will not be published. Required fields are marked *