JavaScript – Lazy Loading Using RequireJS
A web application, however easy or complex it is, consists of a handful of HTML, JavaScript and CSS files. Most of the times application developers use third party JavaScript libraries like jQuery, Knockout, Underscore etc to speed up the development. Since most of these JavaScript libraries were built for a specific purpose and were ‘proven’, it makes sense to refer them as-is rather than implementing the required functionality from scratch. However as the application complexity grows it becomes extremely important to write cleaner, loosely coupled and maintainable code. In this article, I will explain how RequireJS library helps application developer to write modular code and perform lazy loading of JavaScript files which improves application performance.
Lets start without RequireJS library and then refactor it using RequireJS in the next section.
The HTML page defined below contains a paragraph element ‘message’. Once user accesses the web page, it displays order Id and customer name information.
Common.JS file contains definition of two modules – ‘Order’ and ‘Customer’. The ‘showData’ function is associated with the web page body, which internally calls ‘write’ function to display output on webpage. For example purpose, I have hard-coded order id as ’1′ and customer name as ‘Prasad in showData function.
<!DOCTYPE html> <html> <head> <title>JavaScript NonRequireJS</title> <script src="common.js" type="text/javascript"></script> </head> <body> <strong>Display data without RequireJS</strong> <p id="message" /> <script type="text/javascript"> showData(); </script> </body> </html>
Common.JS
function write(message) {
document.getElementById('message').innerHTML += message + '</br>';
}
function showData() {
var o = new Order(1, "Prasad");
write("Order Id : " + o.id + " Customer Name : " + o.customer.name);
}
function Customer(name) {
this.name = name;
return this;
}
function Order(id, customerName) {
this.id = id;
this.customer = new Customer(customerName);
return this;
}
Open the web page in your browser and you should get output as shown below
Even though above code displays the output, there are few issues with it -
- Common.JS file contains definitions of all the required functionalities[write, showData functions] and modules [Order, Customer] which is difficult to maintain and cannot be easily reused. Assume if you want to reuse ‘write’ function in another web page and if you refer to above JavaScript file then you’re importing other functions and modules which might not be required in the web page.
- ‘Order’ module [or class in object oriented term] during initialization creates an instance of ‘Customer’ module. That means Order module has dependency on Customer module. The tight coupling between these modules makes it difficult to refactor / maintain the code for future enhancement.
- As soon as a client makes a request to the web page, Common.JS file gets loaded into the DOM. In above example, even though we need to display output on page load, we already have all the modules [Customer, Order] loaded into the memory which are not required. Loading unnecessary application assets like JavaScript, CSS, Image files can degrade application performance.
- Modules defined in Common.JS files can be splitted into different JavaScript files, however as the application complexity grows it becomes difficult to identify the dependency between JavaSctipt files and the order in which they need to be loaded.
RequireJS library handles the dependency between JavaScript files, loads them on demand and in required order.
Setting up app with RequireJS
Lets take a look at the refactored code now. HTML code defined below refers to Require.JS file. The ‘data-main’ attribute defines the single entry point for the web page. In below case it tells RequireJS to load Main.JS file during start-up.
<!DOCTYPE html> <html> <head> <title>JavaScript RequireJS</title> <script src="Require.Js" type="text/javascript" data-main="Main.js"></script> </head> <body> <strong>Display data using RequireJS</strong> <p id="message" /> </body> </html>
Main.JS
Since this file has been defined using data-main attribute, RequireJS will load this file as soon as possible. This file uses RequireJS library functionality to identify / define the dependency on external JavaScript file. In below code snippet, first parameter indicates the dependency [Order.JS file in this case] and second parameter indicates the callback function. RequireJS identifies all the dependencies and loads them appropriately before executing the callback function. Please note that the value of first parameter [Order in this case] must match the JavaScript file name [Order.JS].
require(["Order"], function (Order) {
var o = new Order(1, "Prasad");
write(o.id + o.customer.name);
});
Order.JS
RequireJS library provides an easy way to define and maintain dependency between JavaScript files. The ‘define’ function mentioned in below code states that, Customer.JS file needs to be loaded before processing ‘Order’ callback function.
define(["Customer"],
function (Customer) {
function Order(id, custName) {
this.id = id;
this.customer = new Customer(custName);
}
return Order;
}
);
Customer.JS
This file does not have dependency on any other JavaScript file, so first parameter value for ‘define’ function is empty.
define([],
function () {
function Customer(name) {
this.name = name;
}
return Customer;
}
);
That is it! Run the application in your browser and you should get output as shown below. However note that RequireJS loads the necessary JavaScript files on-demand, that is when they are absolutely required.
Summary
In this article, we have analyzed RequireJS library which handles the dependency between different JavaScript files and loads them on demand. It helps application developer to write loosely coupled, modular and maintainable code.
Thanks.
Download the Source Code: Lazy Loading using RequireJS (Prasad Honrao, Codetails)
Prasad Honrao
Prasad works as an Architect in Technology Consulting Group [TCG] at Cognizant in UK where he has spent past few years developing Windows and web based applications for Banking and Financial Services domain. Apart from development, he also helps developers to understand and get the best from the Microsoft platform. He primarily works on technologies like ASP.Net MVC, HTML, JavaScript, Windows forms, VSTO and recently have started exploring Windows 8, Windows Store Apps. He is Microsoft Certified Technology Specialist in Web Application Development, Windows Communication Foundation and Microsoft Certified Solution Developer in .Net framework 2.0.
Related posts:
- [Expired] Free Certification for HTML5 with JavaScript & CSS3 Microsoft is encouraging people to develop apps for windows 8...
One Response to JavaScript – Lazy Loading Using RequireJS
Start Contributing!
If you have the knack of writing to share your knowledge with other spirited minds, you can register yourself and get started...
For more information, please visit our Contribute page
Register / Sign In
Information classified
- Announcements (1)
- Code (17)
- .NET (13)
- CSS and HTML (1)
- Database (1)
- Java (1)
- Javascript (1)
- Open Source (6)
- Web Services (1)
- Design (1)
- How-to (18)
- Office 365 (1)
- Server (4)
- SharePoint (8)
- TDD (4)
- Windows 8 (3)
- Presentations (1)
- Promotions (6)
- Uncategorized (1)
Latest on the Stack
- Complete guide to dynamic keyword in C#
- Sharing code: Adding NavigationService
- Mock driven development using .NET
- XecMe – Windows Service Host
- How to Write Access 2013 Custom Web App on Office 365
- Portable Class Library – Articles and Sample References
- Extension SDKs in Build Server without installing it!
- SharePoint 2013 and Search with REST API and ODATA
- Search Engine Changes in SharePoint 2013
- Consuming Odata Service in Windows Store Apps (Include MVVM Pattern)
Twitter Updates
- Complete guide to dynamic keyword in C# is.gd/Emmaju #net #development 2 hours ago
- XecMe - Windows Service Host is.gd/0fjCQb #windowsservices #xecme 6 hours ago
- Sharing code: Adding #NavigationService is.gd/0DDj9G #SharingCode #WindowsPhoneapp #WindowsStoreApps 10 hours ago
- Mock driven development using .NET is.gd/GeHGLe 10 hours ago
- Complete guide to dynamic keyword in C# is.gd/Emmaju #net #development 18 hours ago
Coming Soon














[...] The original article JavaScript – Lazy Loading Using RequireJS [...]