RequireJS with AngularJS

'RequireJS with AngularJS' 
Click here for detailed blog: 

#requirejs #angularjs

  • The very first loading of the application results in downloading all the JavaScript files needed for the whole application into the browser.
  • Define() allows us to build a dependency tree.
  • So the global define() builds a tree of dependencies we are mentioning.
  • If there are no dependencies, the ready handler returns the AMD value immediately.
  • Load Dependency – Determines which class or files needed to be loaded in what order.

What is RequireJS ? RequireJS is a JavaScript file loader or module loader. As the name suggests, requirejs helps us to load the JavaScript files, modules,

@inapp: ‘RequireJS with AngularJS’
Click here for detailed blog:

#requirejs #angularjs

What is RequireJS ?

RequireJS is a JavaScript file loader or module loader. As the name suggests, requirejs helps us to load the JavaScript files, modules, libraries or plugins (along with their dependencies) only when we require them.

Why RequireJS ?

Normal web applications which uses MVC patterns of coding in the front-end are working in such a way that:-

These facts clearly implies that, the index.html is getting uglier as the application grows. You can neither blindly guess the order of the plugins, libraries or custom files nor place them in the index.html in random. And the very first loading of the application is going to be time consuming, even if the launching page – usually login page – doesn’t require most of the custom files, libraries or plugins which are getting loaded.

Here comes the relevance of RequireJS.

How RequireJS ?

         

          During the development, you will be having more script files, but you don’t have to mention any of them inside the

          index.html page, but main.js specified at data-main of this script tag will include them. Hence the index.html page

          looks good.

RequireJS Concepts:-

Diving fast into the concepts of RequireJS; there are four dependency types, four great features and three simple APIs.

The four Dependency Types are as follows:-

The four great features are as follows:-

Before discussing about those three APIs, take a look at application of RequireJS in AngularJS.

By clubbing above mentioned 4 dependency types and 4 great features with AngularJS, a nice scenario has been evolved that, RequireJS can manage load dependency and runtime dependency where as AngularJS can manage constructor dependency and module dependency. Hence the outcome is that; confusion about the order of dependencies is vanished, anxiety about the initial load is resolved.

Back to the essentials of RequireJS, there are 3 simple APIs; define(), require() and config().

Sample code:-

define(“file3”, [“file1”, “file2”, function( file1, file2){

                                                return{

So the consolidation is that, an AMD will be a useful one, only after all the dependencies are resolved and we can  specify these dependencies in any order we want. If there are no dependencies, the ready handler returns the AMD value immediately. The key thing is that, this returned value is about to inject into other AMDs as their dependencies. That is there exists a tree of dependencies.

We can use AMD1 only after chain of dependencies are resolved. So the global define() builds a tree of dependencies we  are mentioning. Then all those ready handlers are fired. They builds a flat registry of values stored by the dependency IDs. These values are usually references or classes. Hence define() allows us to build a dependency tree.

But nothing happens until we say, we want to start the trigger! require() helps us to do this.

Sample code:- 

require([“modulename”]);               

Sample code :- 

require.config ({

                                                paths : {

                                                                ‘filepath1’ : bowerPath + ‘file1/file1.min’

Better use bower tool for downloading the plugins, libraries, cdn files. Because bower takes care of hunting, finding, downloading and saving the JavaScript stuff we are looking for.

What is the advantage of using bower than mentioning the mentioning the libraries manually?

Normally we specified the JavaScript files by the CDN/source path within the application. What about some changes in  the library such as we need the updated version of the same library? Of course we will have to change the version  specification of CDN or download the new version and replace it within the application, build the application again and  deploy. For a deployed application it doesn’t sound good. Think about updating the changes or version automatically. Bower helps us to do this.

Bower is a package manager. To utilize bower, prerequisites for the system are npm and bower. Bower has a config file as bower.json where we mention a specific version, version of a specific series, latest version or latest of the library. Bower has a default bower_components folder where all the all the libraries mentioned in the bower.json are getting downloaded automatically into this folder. We just need to mention this path properly in your main.js only once. Bower will take care of any kind of updation, version changes up-to-date. We don’t have to change them manually.

Sample code:-

                “name”: “project_name”,

                “version”: “1.0”,

                “description”: “project_description”,

                “license”: “MIT”,

                “ignore”: [

                                “node_modules”,

                                “bower_components”,

                                “test”,

                                “tests”

                “dependencies”: {

                                “requirejs”: “~2.1.18”,

                                “angular”: “1.3.8”,

                “authors”: [

                                “manager”

So what would be the out come of all these discussions?

Demo application structure :-

      Demo

Demo application code :-

index.html 

               

                               

                               

                               

                                               

                                               

                               

                               

                                               

                               

                 

main.js 

                var baseUrl = “../../demo2/js”;

                require.config({

                                baseUrl: location.href + ‘/../’,          // alias libraries paths

                                paths: {

                                                ‘angular’  : baseUrl+’/bower_components/angular’,

                                                ‘ngRoute’  : baseUrl+’/bower_components/angular-route’,

                                                ‘app’      : ‘scripts/app’,

                                                ‘loginCtrl’: ‘scripts/controllers/loginController’,

                                                ‘homeCtrl’ : ‘scripts/controllers/homeController’,

                                shim: {

                                                ‘angular’: {

                                                                exports: ‘angular’

                                                ‘ngRoute’: {

                                                                deps: [‘angular’]

                                deps: [‘./bootstrap’]            // kick start application

bootstrap.js :- 

                define([‘require’,’app’], function (require) {

                                ‘use strict’;

                                angular.bootstrap(document, [‘webapp’]);

app.js :- 

                define([‘angular’, ‘ngRoute’], function () {

                                var app = angular.module(“webapp”, [‘ngRoute’]);

                                app.config([‘$routeProvider’, ‘$controllerProvider’, ‘$provide’,

                                                function ($routeProvider, $controllerProvider,        $provide) {

                                                                                controller: $controllerProvider.register,

                                                                                factory: $provide.factory

                                                function resolveController(names) {

                                                                                load: [‘$q’, ‘$rootScope’, function ($q, $rootScope) {

                                                                                                 var defer = $q.defer();

                                                                                                require(names, function () {

                                                                                                defer.resolve();

                                                                                                $rootScope.$apply();

                                                                                return defer.promise;

                                $routeProvider

                                .when(“/login”, {

                                                templateUrl: “partials/login.html”,

                                                controller: “loginCtrl”,

                                                resolve: resolveController([“loginCtrl”])

                                .when(“/home”, {

                                                templateUrl: “partials/home.html”,

                                                controller: “homeCtrl”,

                                                resolve: resolveController([“homeCtrl”])

                                .otherwise({redirectTo: ‘/login’})

                                return app;

loginController.js :- 

                define([‘app’], function (app) {

                                app.register.controller(‘loginCtrl’, [‘$scope’, ‘$location’, function ($scope, $location) {

                                                $scope.title = “Login”;

RequireJS with AngularJS