I am here to continue the discussion around AngularJS. Today, we will discuss how to perform lazy loading or on demand loading of angular js related files using RequireJS. Also in case you have not had a look at our previous articles of this series, go through the following links:
- Learn AngularJS From Beginning: Basic - Part One
- Learn AngularJS From Beginning: Filter - Part Two
- Learn AngularJS From Beginning: Service - Part Three
- Learn AngularJS From Beginning: Directive - Part Four
- Learn AngularJS From Beginning: Form Data Binding - Part Five
- Learn AngularJS From Beginning: Global Object Service - Part Six
- Learn AngularJS From Beginning: Http Request or Ajax - Part Seven
- Learn AngularJS From Beginning: Rest API - Part Eight
- Learn AngularJS From Beginning: Route Url - Part Nine
- Learn AngularJS From Beginning: Animation - Part Ten
- Learn AngularJS From Beginning: Injection - Part Eleven
- Learn AngularJS From Beginning: Localisation - Part Twelve
- Learn AngularJS From Beginning: Unit Test of AngularJS Controller - Part Thirteen
- Learn AngularJS From Beginning: Unit Test of AngularJS Component - Part Fourteen
- Learn AngularJS From Beginning: Automatic Workflow (Grunt) - Part Fifteen
In this article, we will discuss how use angularjs with require js.
Organizing modules with RequireJS and AMD
RequireJS is a popular script loader written by James Burke - a developer who has been quite instrumental in helping shape the AMD module format, which we’ll discuss more shortly. Some of RequireJS’s capabilities include helping to load multiple script files, helping define modules with or without dependencies and loading in non-script dependencies such as text files.
RequireJS is compatible with the AMD (Asynchronous Module Definition) format, a format which was born from a desire to write something better than the “write lots of script tags with implicit dependencies and manage them manually” approach to development. In addition to allowing you to clearly declare dependencies, AMD works well in the browser, supports string IDs for dependencies, declaring multiple modules in the same file and gives you easy-to-use tools to avoid polluting the global namespace. Think about the GMail web-client for a moment. When users initially load up the page on their first visit, Google can simply hide widgets such as the chat module until a user has indicated (by clicking “expand”) that they wish to use it. Through dynamic dependency loading, Google could load up the chat module only then, rather than forcing all users to load it when the page first initializes. This can improve performance and load times and can definitely prove useful when building larger applications.
Writing AMD modules with RequireJS
As discussed above, the overall goal for the AMD format is to provide a solution for modular JavaScript that developers can use today. The two key concepts you need to be aware of when using it with a script-loader are a define() method for facilitating module definition and a require() method for handling dependency loading. As you can tell by the inline comments, the module_id is an optional argument which is typically only required when non-AMD concatenation tools are being used (there may be some other edge cases where it’s useful too). When this argument is left out, we call the module “anonymous”. When working with anonymous modules, the idea of a module’s identity is DRY, making it trivial to avoid duplication of filenames and code. Back to the define signature, the dependencies argument represents an array of dependencies which are required by the module you are defining and the third argument (“definition function”) is a function that’s executed to instantiate your module. A barebone module (compatible with RequireJS) could be defined using define() as follows:
- define(['foo', 'bar'],
- // module definition function
- // dependencies (foo and bar) are mapped to function parameters
- function(foo, bar)
- {
- // return a value that defines the module export
- // (i.e the functionality we want to expose for consumption)
- // create your module here
- var myModule =
- {
- doStuff: function()
- {
- console.log('Yay! Stuff');
- }
- }
- return myModule;
- });
Alternate syntax
There is also a sugared version of define() available that allows you to declare your dependencies as local variables using require(). This will feel familiar to anyone who’s used node, and can be easier to add or remove dependencies. Here is the previous snippet using the alternate syntax:
- define(function(require)
- {
- // module definition function
- // dependencies (foo and bar) are defined as local vars
- var foo = require('foo'),
- bar = require('bar');
- // return a value that defines the module export
- // (i.e the functionality we want to expose for consumption)
- // create your module here
- var myModule =
- {
- doStuff: function()
- {
- console.log('Yay! Stuff');
- }
- }
- return myModule;
- });
The require() method is typically used to load code in a top-level JavaScript file or within a module should you wish to dynamically fetch dependencies. An example of its usage is:
- // Consider 'foo' and 'bar' are two external modules
- // In this example, the 'exports' from the two modules loaded are passed as
- // function arguments to the callback (foo and bar)
- // so that they can similarly be accessed
- require(['foo', 'bar'], function(foo, bar)
- {
- // rest of your code here
- foo.doSomething();
- });
- <!DOCTYPE html>
- <html>
- <head>
- <title>AngularJS Filter</title>
- <link href="../../RefStyle/bootstrap.min.css" rel="stylesheet" />
- <script src="require.js" data-main="app/main.js"></script>
- </head>
- <body data-ng-controller="FilterController" data-ng-cloak>
- <div class="panel panel-default">
- <div class="panel-heading">
- <h3>
- Products
- <span class="label label-primary">{{products.length}}</span>
- </h3>
- </div>
- <div class="panel-body">
- <table class="table table-striped table-bordered table-condensed">
- <thead>
- <tr>
- <td>Name</td>
- <td>Category</td>
- <td>Offer Date</td>
- <td class="text-right">Quantity</td>
- <td class="text-right">Price</td>
- </tr>
- </thead>
- <tbody>
- <tr data-ng-repeat="p in products | orderBy :'name'">
- <td>{{p.name | uppercase}}</td>
- <td>{{p.category | lowercase}}</td>
- <td>{{getExpiryDate(p.expiry) | date:"dd MMM yy"}}</td>
- <td class="text-right">{{p.quantity | number:2 }}</td>
- <td class="text-right">{{p.price | currency}}</td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- </body>
- </html>
- require.config({
- urlArgs: "bust=" + (new Date()).getTime(),
- paths: {
- 'angular': '../../ch20(RequireJs)/angular',
- 'FilterController': 'Index'
- },
- shim: {
- 'angular': {
- exports: 'angular'
- },
- 'app': {
- deps:
- ['angular']
- },
- 'FilterController': {
- deps: ['app']
- },
- },
- deps: ['app']
- });
- require(['FilterController'], function () {
- angular.bootstrap(document, ['TestApp']);
- });
- define(['require'], function (require) {
- var testApp = angular.module('TestApp', []);
- testApp.run(['$rootScope', function ($rootScope) {
- }]);
- });
- define(['angular'], function (angular) {
- var testApp = angular.module('TestApp');
- testApp.controller('FilterController', ['$scope', function ($scope) {
- $scope.products = [
- { name: "Sony LED", category: "TV", price: 40000, quantity: 10, expiry: 30 },
- { name: "Samsung", category: "TV", price: 35640, quantity: 08, expiry: 21 },
- { name: "Z30", category: "Mobile", price: 36000, quantity: 5, expiry: 50 },
- { name: "Iphone 6", category: "Mobile", price: 55000, quantity: 6, expiry: 60 },
- { name: "Galaxy Note 3", category: "Mobile", price: 45000, quantity: 15, expiry: 50 },
- ];
- $scope.getExpiryDate = function (days) {
- var now = new Date();
- return now.setDate(now.getDate() + days);
- }
- }]);
- });

Former memberPosted May 12, 2017, 8:06 AM
You should give the code in zip format so anyone can download and run the code in his pc. thanks
Vignesh ManiPosted May 25, 2016, 8:26 AM
Nice
Pritam ZopePosted May 25, 2016, 5:23 AM
Good one.........................!
Muhammad Aqib ShehzadPosted May 25, 2016, 1:15 AM
nice.......
Gowtham RajamanickamPosted May 25, 2016, 1:14 AM
Good one..
Munesh SharmaPosted May 25, 2016, 12:27 AM
good one
Sonu ChaudharyPosted May 24, 2016, 12:46 PM
Nice Sharing..
Kuppurasu NagarajPosted May 24, 2016, 12:04 PM
Nice Sharing..
Jayant KulkarniPosted May 24, 2016, 11:23 AM
Very Useful.. Thanks for Sharing...