Quantcast
Channel: codetails » HTML5
Viewing all articles
Browse latest Browse all 2

JavaScript – Lazy Loading Using RequireJS

0
0

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

NonRequireJS_PrasadHonrao_Codetails

Even though above code displays the output, there are few issues with it –

  1. 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.
  2. ‘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.
  3. 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.
  4. 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.

RequireJS_PrasadHonrao_Codetails

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)


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images