search
HomeWeb Front-endJS TutorialRequire.js implements js modular management tutorial

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>

The code in a.js

alert("require");

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>

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;]
        }
    }
});

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 ("这是一个无依赖模块")
    }
});

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

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

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

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

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

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

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

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

这里定义了一个名为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);
        }
    }
});

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);
        }
    }
});

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

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool