search
HomeWeb Front-endJS TutorialExplanation on calling js in Require in JavaScript
Explanation on calling js in Require in JavaScriptJan 20, 2018 pm 01:31 PM
javascriptrequire

This article mainly brings you an example sharing of Require calling js in JavaScript. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

When I first started writing JavaScript functions, it usually looked like this:


function fun1() {
 // some code here
}
function fun2() {
 // some other code here
}
...

The functions were all written in the global environment, and when the project was small , usually there will be no conflict issues.

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 the 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 add a closure Import 1 public API interface: www.jb51.net


(function($, mod1) {
 // some code here
 mod1.func1.apply({},['arg1',arg2]);
}(jQuery, com.zfanw.module1));
...

At this point, the possibility of code conflict is very small, but the problem of code dependency, multiple scripts Problems of file management and blocking gradually surfaced – the namespace method began to be used.

So Require.js2 appears.

Require.js

First understand the concept of module 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 for global objects. Reference – Dependencies also do not pollute the global space.

Define the module

Different from the long namespace method above, require.js uses the global method define to define the module, 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

Dependent modules 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, the '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 the module name

#define function has three parameters. The first id is the module name. The format of this name is relative to the path of baseUrl excluding the file format, such as baseUrl is the js directory, and a module is placed in js/libs/hi.js. If the name is defined like this:

##

define('libs/hi', ['jquery'], function($){......});

The advantage of this definition form is that, Module conflicts are impossible 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 after setting the module name of 'libs/hi', the module must be placed in the hi.js file in the js/libs directory. If you want to move the location, the module name Follow the changes. As for the module name generated during later optimization using r.js, that is another matter.

Using modules

After defining various modules with "dependencies" and "no dependencies", how should we use them? Require.js provides a function, require (equivalent to requirejs).

require function loads dependencies and executes callbacks. Unlike define, it does not register callback result 4 as a module:


##
require(['jquery'], function($) { // 这个函数加载 jquery 依赖,然后执行回调代码
 console.log($);
});

Give a simple example. I have a folder with the following file structure:

index.html
 js/
  main.js
  require.js
  jquery.js

Here jquery.js has been registered as an AMD module, and require.js is referenced in the HTML file like this:

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

require.js will check the data-main attribute value, here is js/main. According to the settings, it will load the main.js file in the js directory.

In the main.js file, I only do one thing, use the jQuery method to get the width of the current window:

require([&#39;jquery&#39;], function($) {
 var w = $(window).width();
 console.log(w);
});

It’s that simple to execute the code.

Non-AMD specification modules

但事情远没有我们想像中那么美好,AMD 只是一种社区规范,并非标准,而且在它出现以前,已经有各种各样的流行库存在,更不用说我们自己早期写的代码,所以我们一定会碰上一堆非 AMD 规范的模块。为了让 require.js 能够加载它们,并且自动识别、载入依赖,我们有两种选择,一、给它们全穿上一个叫 define 的函数;二、使用 Require.js 提供的配置选项 shim,曲线救国。

比如我手上一个项目,因为某种原因,还在用 jQuery 1.4.1 版本,而 jQuery 是从1.7版本开始才注册为 AMD 模块的,我要在 require.js 中使用,就需要先做 shim:


require.config({
 shim: {
  &#39;jquery-1.4.1&#39;: { // <= 这个是相对于 main.js 的路径www.45it.com
   exports: &#39;jQuery&#39; // <= 这个值需要稍加注意,稍后会提及
  },
  &#39;libs/jquery-throttle-debounce.min&#39;: { // <= jQuery 插件
   deps: [&#39;jquery-1.4.1&#39;] //无需 exports,因为我们只是在增强 jQuery 功能
  }
 },
});
require([&#39;jquery-1.4.1&#39;, &#39;libs/jquery-throttle-debounce.min&#39;], function($){
 console.log($.debounce);
});

写完 shim,发现 jquery-1.4.1、libs/jquery-throttle-debounce.min 这样的名称有点长。这里我们又有两种选择,一是直接打开修改 js 文件名,或者使用 require.js 提供的配置项 paths 给模块 ID 指定对应的真实文件路径:


require.config({
 paths: {
  &#39;jquery&#39;: &#39;jquery-1.4.1&#39;, // <= 模块 jquery 指向 js/jquery-1.4.1.js 文件
  &#39;debounce&#39;: &#39;libs/jquery-throttle-debounce.min&#39;
 },
 shim: {
  &#39;jquery&#39;: {
   exports: &#39;$&#39;
  },
  &#39;debounce&#39;: {
   deps: [&#39;jquery&#39;]
  }
 }
});
require([&#39;jquery&#39;, &#39;debounce&#39;], function($){
 console.log($.debounce);
});

这样,引用起来就方便多了。

另外,需要注意 shim 中的 exports 项,它的概念更接近 imports,即把全局变量导入。我们如果把 exports 值改成非全局变量名,就会导致传入回调的对象变成 undefined,举个例子:


require.config({
 paths: {
  &#39;jquery&#39;: &#39;jquery-1.4.1&#39;,
 },
 shim: {
  &#39;jquery&#39;: {
   exports: &#39;hellojQuery&#39; // 这里我把 exports 值设置为 jQuery/$ 以外的值
  }
 }
});
require([&#39;jquery&#39;], 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 src="js/a.js"></script>
 <script src="js/b.js"></script>
 <script src="js/c.js"></script>

换句话说,传统的 script 方法里,我们极可能要靠记忆或者检查模块内容这种方式来确定依赖 – 效率太低,还费脑。

减少全局冲突

通过 define 的方式,我们大量减少了全局变量,这样代码冲突的概率就极小极小 – JavaScript 界有句话说,全局变量是魔鬼,想想,我们能减少魔鬼的数量,我想是件好事。

关于全局变量

有一点需要说明的是,require.js 环境中并不是只有 define 和 require 几个全局变量。许多库都会向全局环境中暴露变量,以 jQuery 为例,1.7版本后,它虽然注册自己为 AMD 模块,但同时也向全局环境中暴露了 jQuery 与 $。所以以下代码中,虽然我们没有向回调函数传入一份引用,jQuery/$ 同样是存在的:


require([&#39;jquery&#39;], function(){
 console.log(jQuery);
 console.log($);
});

相关推荐:

a标签不能调用js方法的问题

iframe子父页面调用js函数示例

php如何调用js方法

The above is the detailed content of Explanation on calling js in Require in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools