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:
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'],
-
-
- function(foo, bar)
- {
-
-
-
- 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)
- {
-
-
- var foo = require('foo'),
- bar = require('bar');
-
-
-
- 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:
-
-
-
-
- require(['foo', 'bar'], function(foo, bar)
- {
-
- foo.doSomething();
- });
For demonstrating the above concept, I simple create a simple angular js program as below which demonstrates some data in a table format.
Index.html
- <!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>
Main.js
- 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']);
- });
App.js
- define(['require'], function (require) {
- var testApp = angular.module('TestApp', []);
-
- testApp.run(['$rootScope', function ($rootScope) {
-
- }]);
- });
Index.js (Controller)
- 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);
- }
- }]);
- });