search
HomeWeb Front-endJS TutorialHow does requireJS implement a module loader?

This article mainly introduces an in-depth understanding of requireJS-implementing a simple module loader. Now I share it with you and give it as a reference.

In the previous article, we have emphasized the importance of modular programming more than once, and the problems it can solve:

① Solve the problem of single-file variable naming conflict

② Solve Front-end multi-person collaboration issues

③ Solving file dependency issues

④ Loading on demand (this statement is actually very false)

⑤......

In order to have a deeper understanding of the loader, I read a little bit of the source code of requireJS, but for many students, the implementation of the loader is still unclear.

In fact, it is not implemented through code, just by reading. If you want to understand a library or framework, you can only have a partial understanding, so today I will implement a simple loader

Loader principle analysis

Distribution合

In fact, a complete module is required to run a program. The following code is an example:

//求得绩效系数
 var performanceCoefficient = function () {
  return 0.2;
 };
 //住房公积金计算方式
 var companyReserve = function (salary) {
  return salary * 0.2;
 };
 //个人所得税
 var incomeTax = function (salary) {
  return salary * 0.2;
 };
 //基本工资
 var salary = 1000;
 //最终工资
 var mySalary = salary + salary * performanceCoefficient();
 mySalary = mySalary - companyReserve(mySalary) - incomeTax(mySalary - companyReserve(mySalary));
 console.log(mySalary);

For my complete salary, the company will have performance rewards, but other The algorithm may be very complex, which may involve attendance rate, completion level, etc. We will not care about

for the time being. If it increases, it will decrease. Therefore, we will pay the housing provident fund and deduct personal income tax. In the end, it is me Salary

The above process is indispensable for a complete program, but each function may be extremely complicated, and things related to money are complicated, so the company's performance alone may exceed 1000 lines of code

So we will start to separate here:

<script src="companyReserve.js" type="text/javascript"></script>
<script src="incomeTax.js" type="text/javascript"></script>
<script src="performanceCoefficient.js" type="text/javascript"></script>
<script type="text/javascript">
 //基本工资
 var salary = 1000;
 //最终工资
 var mySalary = salary + salary * performanceCoefficient();
 mySalary = mySalary - companyReserve(mySalary) - incomeTax(mySalary - companyReserve(mySalary));
 console.log(mySalary);
</script>

The above code appears to be "separated", but in fact it also causes Having solved the problem of "combination", how can I put them back together well? After all, the files may also involve dependencies. Here we enter our require and define

require and define

In fact, the above solution is still divided by files, not by modules. If the file name changes, the page will be involved in the change. In fact, there should be a path mapping here. To deal with this problem

var pathCfg = {
 &#39;companyReserve&#39;: &#39;companyReserve&#39;,
 &#39;incomeTax&#39;: &#39;incomeTax&#39;,
 &#39;performanceCoefficient&#39;: &#39;performanceCoefficient&#39;
};

So one of our modules corresponds to a path js file, and the rest is to load the corresponding module, because the front-end module involves requests. So this way of writing:

companyReserve = requile(&#39;companyReserve&#39;);

is not applicable to the front end. Even if you see it done somewhere, there must be some "tricks" in it. Here we need to follow the AMD specification. :

require.config({
 &#39;companyReserve&#39;: &#39;companyReserve&#39;,
 &#39;incomeTax&#39;: &#39;incomeTax&#39;,
 &#39;performanceCoefficient&#39;: &#39;performanceCoefficient&#39;
});
require([&#39;companyReserve&#39;, &#39;incomeTax&#39;, &#39;performanceCoefficient&#39;], function (companyReserve, incomeTax, performanceCoefficient) {
 //基本工资
 var salary = 1000;
 //最终工资
 var mySalary = salary + salary * performanceCoefficient();
 mySalary = mySalary - companyReserve(mySalary) - incomeTax(mySalary - companyReserve(mySalary));
 console.log(mySalary);
});

Here is a standard way of writing requireJS. First define the module and its path mapping, and define the dependencies

require(depArr, callback)

A simple and complete module loader basically looks like this , first is an array of dependencies, and second is a callback. The callback requires all dependencies to be loaded before it can run, and the parameters of the callback are the results of the execution of the dependencies, so the define module is generally required to have a return value

Scheme Yes, so how to achieve it?

Implementation plan

When it comes to module loading, people’s first reaction is ajax, because whenever they can get the content of the module file, it is modular. Basic, but using ajax is not possible because ajax has cross-domain problems

And the modular solution inevitably has to deal with cross-domain problems, so it is convenient to use dynamically created script tags to load js files It has become the first choice, but the solution that does not use ajax still has requirements for the difficulty of implementation

PS: In our actual work, there will also be scenes of loading html template files, we will talk about this later

Usually we do this, require is used as the program entrance to schedule javascript resources, and after loading into each define module, each module will silently create a script tag to load

After the loading is completed, go to the require module The queue reports that it has finished loading. When all the dependent modules in require have been loaded, its callback will be executed.

The principle is roughly the same. The rest is just the specific implementation, and then we can prove whether this theory is reliable.

Loader castration implementation

Core module

Based on the above theory, we will start with the three basic functions of the entrance as a whole

var require = function () {
};
require.config = function () {
};
require.define = function () {
};

These three modules are indispensable:

① config is used to configure the mapping between modules and paths, or has other uses

② require is the program entrance

③ define design Each module responds to the schedule of require

Then we will have a method to create a script tag and listen to its onLoad event

④ loadScript

Next we load the script tag Finally, there should be a global module object used to store loaded modules, so two requirements are proposed here:

⑤ require.moduleObj module storage object

⑥ Module, module The constructor

With the above core modules, we formed the following code:

(function () {
 var Module = function () {
  this.status = &#39;loading&#39;; //只具有loading与loaded两个状态
  this.depCount = 0; //模块依赖项
  this.value = null; //define函数回调执行的返回
 };
 var loadScript = function (url, callback) {
 };
 var config = function () {
 };
 var require = function (deps, callback) {
 };
 require.config = function (cfg) {
 };
 var define = function (deps, callback) {
 };
})();

So the next step is the specific implementation, and then during the implementation process, we will make up for the unavailable interfaces and details, often The final implementation has nothing to do with the original design...

Code implementation

这块最初实现时,本来想直接参考requireJS的实现,但是我们老大笑眯眯的拿出了一个他写的加载器,我一看不得不承认有点妖

于是这里便借鉴了其实现,做了简单改造:

(function () {
 //存储已经加载好的模块
 var moduleCache = {};
 var require = function (deps, callback) {
  var params = [];
  var depCount = 0;
  var i, len, isEmpty = false, modName;
  //获取当前正在执行的js代码段,这个在onLoad事件之前执行
  modName = document.currentScript && document.currentScript.id || &#39;REQUIRE_MAIN&#39;;
  //简单实现,这里未做参数检查,只考虑数组的情况
  if (deps.length) {
   for (i = 0, len = deps.length; i < len; i++) {
    (function (i) {
     //依赖加一
     depCount++;
     //这块回调很关键
     loadMod(deps[i], function (param) {
      params[i] = param;
      depCount--;
      if (depCount == 0) {
       saveModule(modName, params, callback);
      }
     });
    })(i);
   }
  } else {
   isEmpty = true;
  }
  if (isEmpty) {
   setTimeout(function () {
    saveModule(modName, null, callback);
   }, 0);
  }
 };
 //考虑最简单逻辑即可
 var _getPathUrl = function (modName) {
  var url = modName;
  //不严谨
  if (url.indexOf(&#39;.js&#39;) == -1) url = url + &#39;.js&#39;;
  return url;
 };
 //模块加载
 var loadMod = function (modName, callback) {
  var url = _getPathUrl(modName), fs, mod;
  //如果该模块已经被加载
  if (moduleCache[modName]) {
   mod = moduleCache[modName];
   if (mod.status == &#39;loaded&#39;) {
    setTimeout(callback(this.params), 0);
   } else {
    //如果未到加载状态直接往onLoad插入值,在依赖项加载好后会解除依赖
    mod.onload.push(callback);
   }
  } else {
   /*
   这里重点说一下Module对象
   status代表模块状态
   onLoad事实上对应requireJS的事件回调,该模块被引用多少次变化执行多少次回调,通知被依赖项解除依赖
   */
   mod = moduleCache[modName] = {
    modName: modName,
    status: &#39;loading&#39;,
    export: null,
    onload: [callback]
   };
   _script = document.createElement(&#39;script&#39;);
   _script.id = modName;
   _script.type = &#39;text/javascript&#39;;
   _script.charset = &#39;utf-8&#39;;
   _script.async = true;
   _script.src = url;
   //这段代码在这个场景中意义不大,注释了
   //   _script.onload = function (e) {};
   fs = document.getElementsByTagName(&#39;script&#39;)[0];
   fs.parentNode.insertBefore(_script, fs);
  }
 };
 var saveModule = function (modName, params, callback) {
  var mod, fn;
  if (moduleCache.hasOwnProperty(modName)) {
   mod = moduleCache[modName];
   mod.status = &#39;loaded&#39;;
   //输出项
   mod.export = callback ? callback(params) : null;
   //解除父类依赖,这里事实上使用事件监听较好
   while (fn = mod.onload.shift()) {
    fn(mod.export);
   }
  } else {
   callback && callback.apply(window, params);
  }
 };
 window.require = require;
 window.define = require;
})();

首先这段代码有一些问题:

没有处理参数问题,字符串之类皆未处理

未处理循环依赖问题

未处理CMD写法

未处理html模板加载相关

未处理参数配置,baseUrl什么都没有搞

基于此想实现打包文件也不可能

......

但就是这100行代码,便是加载器的核心,代码很短,对各位理解加载器很有帮助,里面有两点需要注意:

① requireJS是使用事件监听处理本身依赖,这里直接将之放到了onLoad数组中了

② 这里有一个很有意思的东西

document.currentScript

这个可以获取当前执行的代码段

requireJS是在onLoad中处理各个模块的,这里就用了一个不一样的实现,每个js文件加载后,都会执行require(define)方法

执行后便取到当前正在执行的文件,并且取到文件名加载之,正因为如此,连script的onLoad事件都省了......

demo实现

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title></title>
</head>
<body>
</body>
<script src="require.js" type="text/javascript"></script>
<script type="text/javascript">
 require([&#39;util&#39;, &#39;math&#39;, &#39;num&#39;], function (util, math, num) {
  num = math.getRadom() + &#39;_&#39; + num;
  num = util.formatNum(num);
  console.log(num);
 });
</script>
</html>
//util
define([], function () {
 return {
  formatNum: function (n) {
   if (n < 10) return &#39;0&#39; + n;
   return n;
  }
 };
});
//math
define([&#39;num&#39;], function (num) {
 return {
  getRadom: function () {
   return parseInt(Math.random() * num);
  }
 };
});
//math
define([&#39;num&#39;], function (num) {
 return {
  getRadom: function () {
   return parseInt(Math.random() * num);
  }
 };
});

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

有关在Vue2.x中父组件与子组件双向绑定(详细教程)

详细介绍在Vue2.0中v-for迭代语法的变化(详细教程)

在vue2.0中循环遍历并且加载不同图片(详细教程)

The above is the detailed content of How does requireJS implement a module loader?. 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
Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

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

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version