Detailed explanation of using Require to call js
This time I will bring you a detailed explanation of how to use Require to call js. What are the precautions for Require to call js? The following is a practical case, let's take a look.
When I first started writing JavaScript functions, it usually looked like this:
function fun1() { // some code here } function fun2() { // some other code here } ...
All functions are written in the global environment. When the project is small, there are usually no conflicts.
But after there were too many codes, I gradually found that the function names (English vocabulary) were a bit insufficient. So the concept of namespace was introduced and modularized code began.
Function under namespace
Under the namespace, my code is written like this:
var com = com || {}; com.zfanw = com.zfanw || {}; com.zfanw.module1 = (function() { // some code here return { func1: func1, ... }; }()); com.zfanw.module2 = (function() { // some other code here return { func1: func1, ... }; }()); ...
In line with the principle of object-oriented, I usually write the execution function like this:
com.zfanw.module1.func1.apply({},['arg1',arg2]); ...
Of course, in order to save typing characters, I will also import a public API interface in the closure: www.jb51.net
(function($, mod1) { // some code here mod1.func1.apply({},['arg1',arg2]); }(jQuery, com.zfanw.module1)); ...
At this point, the possibility of code conflicts has been very small, but the problems of code dependency, multi-script file management, and blocking have gradually surfaced - the namespace method has begun to become urgent.
So Require.js2 comes into play.
Require.js
First understand the concept of modules in require.js 3:
A module is different from a traditional script file in that it defines a well-scoped object that avoids polluting the global namespace. It can explicitly list its dependencies and get a handle on those dependencies without needing to refer to global objects, but instead receive the dependencies as arguments to the function that defines the module.
Simply put, there are two points. First, the module scope is self-contained and does not pollute the global space; second, the module specifies dependencies, and dependencies are imported through parameter passing without the need to reference global objects – dependencies also do not pollute. global space.
Define module
Different from the long namespace method above, require.js uses the global method define to define modules, in the following form:
define(id?, dependencies?, factory); // ? 表示可选项
Let me divide the modules into two types.
Dependency-free modules
If a module does not depend on other modules, it is very simple to define. For example, the module hello is placed in the hello.js file:
define(function() { // some code here return { // some public api }; });
Dependent modules
Modules with dependencies are a little more complicated. When defining, we need to list the dependencies of the module:
define(['jquery'], function($) { // 比如这个模块,代码的执行依赖 jQuery,require.js 会先加载 jquery 模块代码,并加以执行,然后将依赖模块 以 $ 的参数形式传入回调函数中,回调函数将执行结果注册为模块 // maybe some code here return { // some public api }; });
Here, 'jquery' in the dependency is the path of the module relative to baseUrl, which is equivalent to the module ID.
Now, go back and look at the code that imports the public API in the closure written above, and compare it with the define function:
(function($, mod1) { // some code here mod1.func1.apply({},['arg1',arg2]); }(jQuery, com.zfanw.module1));
In this code, I also imported jQuery. In the closure, I also accessed jQuery through the $ external parameter. It can be said that its way of "defining dependencies" is very similar to the define method. The difference is that the jquery imported by define is not a global variable, so it will not pollute the global environment.
About module name
The define function has three parameters. The first id is the module name. The format of this name is the path relative to baseUrl minus the file format. For example, baseUrl is the js directory and a module is placed in js/libs/hi.js. If the name It is defined like this:
define('libs/hi', ['jquery'], function($){......});
The advantage of this definition is that modules cannot conflict because files with the same name are not allowed in the same directory. But therefore require.js recommends that we not set the module name, because setting After the module name of ‘libs/hi’, the module must be placed in hi.js in the js/libs directory. In the file, if the location is moved, the module name must be changed accordingly. As for the module name generated during later optimization using r.js, that is another matter.
Use modules
After defining various modules with "dependencies" and "without dependencies", how should we use them? Require.js provides a function, require (equivalent to requirejs).
require 函数加载依赖并执行回调,与 define 不同的是,它不会把回调结果4注册成模块:
require(['jquery'], function($) { // 这个函数加载 jquery 依赖,然后执行回调代码 console.log($); });
举一个简单的例子。我有一个文件夹,文件结构如下:
index.html js/ main.js require.js jquery.js
这里 jquery.js 已经注册为 AMD 模块,则 HTML 文件里这样引用 require.js:
<script></script>
require.js 会检查 data-main 属性值,这里是 js/main,根据设定,它会加载 js 目录下的 main.js 文件。
main.js 文件里,我只干一件事,用 jQuery 方法取得当前窗口的宽度:
require(['jquery'], function($) { var w = $(window).width(); console.log(w); });
执行代码就这么简单。
非 AMD 规范的模块
但事情远没有我们想像中那么美好,AMD 只是一种社区规范,并非标准,而且在它出现以前,已经有各种各样的流行库存在,更不用说我们自己早期写的代码,所以我们一定会碰上一堆非 AMD 规范的模块。为了让 require.js 能够加载它们,并且自动识别、载入依赖,我们有两种选择,一、给它们全穿上一个叫 define 的函数;二、使用 Require.js 提供的配置选项 shim,曲线救国。
比如我手上一个项目,因为某种原因,还在用 jQuery 1.4.1 版本,而 jQuery 是从1.7版本开始才注册为 AMD 模块的,我要在 require.js 中使用,就需要先做 shim:
require.config({ shim: { 'jquery-1.4.1': { // <p style="text-align: left;"> 写完 shim,发现 jquery-1.4.1、libs/jquery-throttle-debounce.min 这样的名称有点长。这里我们又有两种选择,一是直接打开修改 js 文件名,或者使用 require.js 提供的配置项 paths 给模块 ID 指定对应的真实文件路径:</p><pre class="brush:php;toolbar:false">require.config({ paths: { 'jquery': 'jquery-1.4.1', // <p style="text-align: left;"> 这样,引用起来就方便多了。</p><p style="text-align: left;"> 另外,需要注意 shim 中的 exports 项,它的概念更接近 imports,即把全局变量导入。我们如果把 exports 值改成非全局变量名,就会导致传入回调的对象变成 undefined,举个例子:</p><pre class="brush:php;toolbar:false">require.config({ paths: { 'jquery': 'jquery-1.4.1', }, shim: { 'jquery': { exports: 'hellojQuery' // 这里我把 exports 值设置为 jQuery/$ 以外的值 } } }); require(['jquery'], function($){ console.log($);// 这里,会显示 undefined });
其他模块在做 shim 时同理,比如 underscore 需要 exports 成 _。
Require.js 的好处
说了这么多,Require.js 到底有什么好处?
并行加载
我们知道,<script></script> 标签会阻塞页面,加载 a.js 时,后面的所有文件都得等它加载完成并执行结束后才能开始加载、执行。而 require.js 的模块可以并行下载,没有依赖关系的模块还可以并行执行,大大加快页面访问速度。
不愁依赖
在我们定义模块的时候,我们就已经决定好模块的依赖 – c 依赖 b,b 又依赖 a。当我想用 c 模块的功能时,我只要在 require函数的依赖里指定 c:
require(['c'], function(c) {...});
至于 c 依赖的模块,c 依赖的模块的依赖模块… 等等,require.js 会帮我们打理。
而传统的 script 办法,我们必须明确指定所有依赖顺序:
<script></script> <script></script> <script></script>
换句话说,传统的 script 方法里,我们极可能要靠记忆或者检查模块内容这种方式来确定依赖 – 效率太低,还费脑。
减少全局冲突
通过 define 的方式,我们大量减少了全局变量,这样代码冲突的概率就极小极小 – JavaScript 界有句话说,全局变量是魔鬼,想想,我们能减少魔鬼的数量,我想是件好事。
关于全局变量
有一点需要说明的是,require.js 环境中并不是只有 define 和 require 几个全局变量。许多库都会向全局环境中暴露变量,以 jQuery 为例,1.7版本后,它虽然注册自己为 AMD 模块,但同时也向全局环境中暴露了 jQuery 与 $。所以以下代码中,虽然我们没有向回调函数传入一份引用,jQuery/$ 同样是存在的:
require(['jquery'], function(){ console.log(jQuery); console.log($); });
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
js css improves the user experience when loading web pages
The above is the detailed content of Detailed explanation of using Require to call js. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
