Home > Web Front-end > JS Tutorial > body text

requireJS implements a simple module loader instance sharing

小云云
Release: 2018-01-16 13:15:23
Original
1603 people have browsed it

This article mainly introduces the in-depth understanding of requireJS-implementing a simple module loader. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

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

② Solving the front-end multi-person collaboration problem

③ Solving the file dependency problem

④ 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 not clear.

In fact, it is not implemented through code. Reading alone can only give you a partial understanding of a library or framework, so today I will implement a simple loader

Loader principle analysis

分和合

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

I have a complete In terms of salary, the company will have performance rewards, but the algorithm may be very complex, which may involve attendance, completion, etc. We will not care about

for the time being. If there is an increase, there will be a decrease, so we will pay housing. The provident fund will also deduct personal income tax, which is ultimately my salary

The above process is indispensable for a complete program, but each function may be extremely complicated and have something to do with money. are all complicated, so the company performance alone may exceed 1,000 lines of code

So we will start to divide it 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 shows that it is "separated", but in fact it also causes the problem of "combining". How can I put them back together again? After all, the files may also involve To dependency, here we enter our require and define

require and define

In fact, the above solution is still divided by files instead of modules. , if the file name changes, the page will be involved in the change. In fact, there should be a path mapping to handle 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, 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 this 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 requireJS way of writing, 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, followed by a callback. The callback requires all dependencies to be loaded before it can run, and The parameter of the callback is the result of the execution of the dependency, so the define module is generally required to have a return value.

Now that we have the solution, how to implement 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 entry

③ define design each module and respond to require scheduling

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

④ loadScript

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

⑤ require.moduleObj module storage object

⑥ Module, the constructor of the module

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

于是接下来便是具体实现,然后在实现过程中补足不具备的接口与细节,往往在最后的实现与最初的设计没有半毛钱关系......

代码实现

这块最初实现时,本来想直接参考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

小结

今天我们实现了一个简单的模块加载器,通过他希望可以帮助各位了解requireJS或者seaJS,最后顺利进入模块化编程的行列。

相关推荐:

用js实现简易模块加载器的方法

概述如何实现一个简单的浏览器端js模块加载器

JavaScript 模块化编程之加载器原理详解

The above is the detailed content of requireJS implements a simple module loader instance sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!