Home Web Front-end JS Tutorial Require.js implements js modular management tutorial

Require.js implements js modular management tutorial

Mar 30, 2017 pm 04:42 PM

What is Require.js

Require.js is an AMD-standard lightweight jsModularizationManagementframework. The latest version of require.js 2.1.11 is only 14.88K after compression. It can divide the js code into one Modules can be loaded asynchronously or dynamically, and the dependencies between modules can be clearly seen, thereby improving code quality, performance and maintainability. The author of Require.js is James Burke, the founder of the AMD specification.

What benefits can Require.js bring?

Below we can give a simple example to illustrate:

Usually our page structure is as follows

<!DOCTYPE html>
<html>
<head>
   <meta charset="UTF-8">
   <title>require</title>
   <script src="js/a.js"></script>
   <script src="js/b.js"></script>
   <script src="js/c.js"></script>
   <script src="js/d.js"></script>
   <script src="js/e.js"></script>
   <script src="js/f.js"></script>
   <script src="js/g.js"></script>
</head>
<body>
<p>require</p>
</body>
</html>
Copy after login

The code in a.js

alert("require");
Copy after login

When running the page, you can find When the alert pops up, you need to click OK to display the content of p. Because the js of the page is rendered synchronously, the rendering of js will inevitably block the subsequent html rendering. Furthermore, introducing a lot of js files is not beautiful, but using require.js can achieve modular asynchronous loading of js.

How to use Require.js

First go to the require.js official website to download the latest version, and then introduce it to the page, as follows:

<script src="js/require.js" data-main="js/main.js"></script>
Copy after login

data-mainAttributecannot be ignored, the file pointed to by data-main is the file where the main code is located , the scripts configured in main.js will be loaded asynchronously, and the directory where main.js is located defaults to the root path.

require.js config

config method is used to configure running parameters. First set the parameters, see the example below:
My project file structure is as follows

Require.js implements js modular management tutorial

The main file main.js

require.config({
    baseUrl: "js",
    paths: {
        "jquery": ["lib/jquery-1.8.3.min"],
        "popup": ["lib/popup"],
        "moduleA": ["app/moduleA"],
        "moduleB": ["appmoduleB"]
    },
    shim: {
        &#39;popup&#39;: {
            deps: [&#39;jquery&#39;]
        }
    }
});
Copy after login

The config method receives an objectparameter. The following explains the role of each attribute.
baseUrl: Set the root path. If this attribute is not set, it will default to the directory where the main file is located. Here, set the JS directory as the root path.
paths: Set the alias and path of each module. Alias ​​must be used when calling the module. The resource file path can be a local path, or an external link, or multiple paths can be set. The path can be a stringpath, or an array. When there are two or more paths, it must be array.
Take the JQ path as an example, a single path "jquery": ["lib/jquery-1.8.3.min"]
Multiple paths "jquery": ["http://apps.bdimg.com/libs/jquery/ 1.8.3/jquery.min.js","lib/jquery-1.8.3.min"], when there are multiple paths, the resource file of the first path will be obtained first. If the first path fails to load, the second path will be loaded. path (Note: In my practice, when the first path uses CDN, the IE browser below IE11 will fail to load and no local resources will be called, the reason is unknown)
shim: Non-AMD standard modules cannot be called directly, this attribute Used to set non-AMD standard modules. The attribute value is an object. The pop-up plug-in I wrote is not AMD standard, so it needs to be set. The set module name and the module name it depends on must be the alias defined by the module in paths. deps is used to set the dependencies of this module. The popup plug-in depends on JQ

define(name,deps,callback)函数

单从语义就应该猜到这个函数用来定于模块,下面解释define函数,若看不懂别着急,后面会举例。
在require.js源码中可以看到有这么一行代码define = function (name, deps, callback) {} ,可知define接收三个参数
name:为可选参数,该模块的标识,字符串类型,通俗来讲就是给该模块取的名称,可自定义,但不能与其他模块名称相同,如果该参数未选,那么该模块的名称为该文件在paths中定义的别名
deps:当前模块的依赖,数组类型,为已定义的模块名称,若不存在依赖该参数可不填
callback:是一个函数或者对象,为函数时,当依赖的模块加载完成后该回调函数将被调用,依赖关系会以参数的形式注入到该函数上,参数与依赖的模块一一对应,(注:如果定义的模块想被其他模块引用需返回一个对象)。

通过define定义模块的方式可分为以下两类。

1. 无依赖模块
也就是说该模块无需依赖其他模块,可以直接定义,如下:

define({
    fnMethod: function() {
        return ("这是一个无依赖模块")
    }
});
Copy after login

该模块只传了一个对象类型的callback,也等价于

define(function() {
    return {
        fnMethod: function () {
            return ("这是一个无依赖模块")
        }
    }
});
Copy after login

该模块则传了一个函数类型的callback,模块定义了一个函数fnMethod,返回一个字符串值,实际上返回值也可以是其他类型,第二种方法只是将函数做为对象返回,建议采用第二种方法来定义无依赖模块。

2. 有依赖模块
定义有依赖模块格式需要稍作改变,格式如下:

 //假如moduleA模块返回了一个属性name,值为“老宋”,<p class="text">老马</p>

 define(["jquery","moduleA"],function($, mA) {    //参数和依赖的模块需一一对应
        return {
            fnMethod: function () {    
                return ($.text(".text") + mA.name);
            }
        }
    });
Copy after login

该例子表明当前模块依赖于jquery和moduleA,返回一个结果“老马老宋”。沿用上面的例子再举一个完整的例子:

 define("module",["jquery","moduleA"],function($, mA) {    //参数和依赖的模块需一一对应
        return {
            fnMethod: function () {    //fnMethod即提供给外部调用的接口
                return ($(".text").text() + mA.name);
            }
        }
 });
Copy after login

这里定义了一个名为module的模块,并且它依赖于jquery和moduleA模块。

当依赖的模块很多的时候再像下面这样写感觉是不是很挫?

define("module", ["jquery", "moduleA", "moduleB", "moduleC", "moduleD", "moduleE", "moduleF"], function ($, mA, mB, mC, mD, mE, mF) {
    return {
        fnMethod: function () {
            return ($(".text").text() + mA.name);
        }
    }
});
Copy after login

require.js2.0版本之后提供了一种更好的写法。

   define("module", function (require) {    //将“require”本身做为一个依赖注入到模块
    var $ = require("jquery"),
        mA = require("moduleA"),
        mB = require("moduleB"),
        mC = require("moduleC"),
        mD = require("moduleD"),
        mE = require("moduleE"),
        mF = require("moduleF");
    
    return {
        fnMethod: function () {
            return ($(".text").text() + mA.name);
        }
    }
});
Copy after login

 以上就是Require.js实现js模块化管理教程的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles