Home  >  Article  >  Web Front-end  >  Using RequireJS to implement lazy loading in JavaScript applications_Basics

Using RequireJS to implement lazy loading in JavaScript applications_Basics

WBOY
WBOYOriginal
2016-05-16 15:52:011056browse

Whether it is simple or complex, web applications are composed of some HTML, JavaScript, and CSS files. Usually developers will use third-party JavaScript frameworks such as JQuery, Knockout, Underscore, etc. to improve development speed. Since these JavaScript frameworks have been developed for specific purposes and have been "proven", it is more appropriate to use them directly than to implement the required functions from scratch. However, as the complexity of applications continues to increase, it becomes increasingly important to write clean, low-coupling, and maintainable code. In this article, I will explain how the RequireJS framework helps application developers write more modular code and how it improves application performance by lazy loading of JavaScript files.

We will not use the RequireJS framework in the beginning, and then reconstruct it using RequireJS in the next chapter.

The following HTML page contains a e388a4556c0f65e1904146cc1a846bee element with the id "message". When the user visits this page, it will display the order ID and customer name information.

The Common.JS file contains the definitions of two modules - Order and Customer. The function showData is combined with the body of the page. It puts the information to be output into the page by calling the write function. As an example, I hardcoded the Id to be 1 and the customer name to be Prasad in the 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 this page in your browser, you will see the following information.

201571120734678.png (300×172)

Although the above code is able to display the output, it still has some problems:

  • The Common.JS file contains all the functions that need to be defined (write, showData), and the modules (Order, Customer) are difficult to maintain and reuse. If you want to reuse the write function in other pages and reference the above JavaScript file, then you have also imported other functions and modules that may not be needed for this page.
  • The Order module (or "class" in object-oriented terms) creates an instance of the Customer module during the initialization process. This means that the Order module depends on the Customer module. The tight coupling between these modules makes it difficult to refactor and maintain during future optimization.
  • Whenever the client requests this page, the Common.JS file will be loaded into the DOM. In the above example, although we only need to output information on the page, we still load those unnecessary modules (Customer, Order) into memory. Loading unnecessary application resources (JavaScript, CSS, image files, etc.) can reduce application performance.
  • The modules in the Common.JS file can be separated into different JavaScript files, but when the application becomes more and more complex, it is difficult to judge the dependencies between JavaScript files and the loading order of files that need to be loaded. .

The RequireJS framework handles dependencies between JavaScript files and loads them sequentially as needed.

Build applications with RequireJS

Now let’s look at the refactored code. The HTML code below references the Require.JS file. The data-main attribute defines the only entry point for this page. In the scenario below, it tells RequireJS to load Main.js on startup.

<!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 specified via the data-main attribute, RequireJS will load it as quickly as possible. This file uses functions of the RequireJS framework to determine and define dependencies on other JavaScript files. In the code snippet below, the first parameter represents the dependency (depending on the Order.JS file), and the second parameter is a callback function. RequireJS analyzes all dependencies and loads them, then executes this callback function. Please note that the value of the first parameter (Order) must be consistent with the file name (Order.JS).

require(["Order"], function (Order) {
  var o = new Order(1, "Prasad");
  write(o.id + o.customer.name);
});

Order.JS

The RequireJS framework provides an easy way to define and maintain dependencies between JavaScript files. The define function in the code below declares that Customer.JS must be loaded before processing the 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 depend on any other JavaScript files, so the value of the first parameter of the define function is an empty array.

define([],
function () {
function Customer(name) {
this.name = name;
}
return Customer;
}
);


Okay, now open this application with your browser and you will see the following output. Note that RequireJS only loads required JavaScript files.

201571120754519.png (300×172)

Summary

In this article, we analyze how the RequireJS framework handles dependencies between JavaScript files and loads them as needed. It helps developers write code that is more loosely coupled, modular, and maintainable.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn