Table of Contents
Loader principle analysis
Loader castration implementation
Home Web Front-end JS Tutorial How does requireJS implement a module loader?

How does requireJS implement a module loader?

Jun 11, 2018 pm 05:54 PM
require

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);
Copy after login

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>
Copy after login

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;
};
Copy after login

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;);
Copy after login

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);
});
Copy after login

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

require(depArr, callback)
Copy after login

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 () {
};
Copy after login

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) {
 };
})();
Copy after login

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;
})();
Copy after login

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

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

未处理循环依赖问题

未处理CMD写法

未处理html模板加载相关

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

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

......

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

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

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

document.currentScript
Copy after login

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

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>
Copy after login
//util
define([], function () {
 return {
  formatNum: function (n) {
   if (n < 10) return &#39;0&#39; + n;
   return n;
  }
 };
});
Copy after login
//math
define([&#39;num&#39;], function (num) {
 return {
  getRadom: function () {
   return parseInt(Math.random() * num);
  }
 };
});
Copy after login
Copy after login
//math
define([&#39;num&#39;], function (num) {
 return {
  getRadom: function () {
   return parseInt(Math.random() * num);
  }
 };
});
Copy after login
Copy after login

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

相关文章:

有关在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 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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles