Home  >  Article  >  Web Front-end  >  How does requireJS implement a module loader?

How does requireJS implement a module loader?

亚连
亚连Original
2018-06-11 17:54:391399browse

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