Home  >  Article  >  Web Front-end  >  Example tutorial on loading JavaScript modules using the RequireJS library

Example tutorial on loading JavaScript modules using the RequireJS library

高洛峰
高洛峰Original
2016-12-28 14:15:17996browse

The default loading method of js through script tags is synchronous, that is, after the js in the first script tag is loaded, the second one starts to be loaded, and so on, until all js files are loaded. And the dependency of js must be ensured through the order of script; during js loading, the browser will stop responding, which greatly affects the user experience. Based on this, many solutions to js loading and unloading have appeared, require js is one of them one.

The modules loaded by requirejs are generally modules that comply with AMD standards, that is, defined with define and ruturn to return modules that expose methods and variables; requirejs can also load modules that meet AMD standards, but it is more troublesome. This time not involving.

require loading js main involves the following aspects:

script tag data-main attribute declares the entry module loaded by requirejs, async="true" (non-ie) and defer(ie) tags indicate asynchronous load.

require.config The path corresponding to the configuration module

require declaration of dependencies

html demo

<script src ="js/require.js" defer async="true" data-main="js/main" >
 
<!--给出requirejs路径,声明为异步加载,指定入口模块为
 
main.js(可省略.js)-->

main.js

require.config({
  //声明模块的位置
  paths: {
    "jquery":"libs/jquery"
    "login" : "libs/login"
  }
  //或使用baseUrl指定所有模块的路径
  baseUrl: "js/libs"
});
//使用require加载模块,第一个参数为数组,即要加载的模块,将按数组顺序加载;第二个为回调函数,在全部加载完成后执行。
require([&#39;jquery&#39;,&#39;login&#39;],function($,Login){
  alert("jquery and login module load success!");
  Login.do_login();
  //some else
});

Conforms amd's login module definition

//依赖jquery的定义
 define([&#39;jquery&#39;],function($){
   // some definations
  function do_login(){
    $.post(&#39;/sessions/create&#39;,{uname:$("#uname").val(),
         password:$("#password").val()},function(data){
     //some 
   });
   return {do_login:do_login};
  } 
 });
 
//不依赖其他模块的定义
define(function(){
 //some definations
 return {xx:xx};
});

rails does not apply a js loader. On the one hand, the asset pipe of the new version of rails will package all js files into one js file, and there is no state of multiple js loading. On the one hand, turbolink uses the so-called pjax technology, which has mixed reviews. The default link is changed to ajax mode, which only obtains the bod part of the html and leaves the head part unchanged, so that js is loaded only when the website is opened for the first time.


Case 1: Load JavaScript file

<script src="./js/require.js"></script> 
  <script> 
 require(["./js/a.js", "./js/b.js"], function() { 
      myFunctionA(); 
      myFunctionB(); 
   }); 
  </script>

The string array parameter in the require method can allow different values. When the string ends with ".js", or with When the string starts with "/" or is a URL, RequireJS will think that the user is loading a JavaScript file directly. Otherwise, when the string is similar to "my/module", it will think that this is a module and will use the user's name to load a JavaScript file. Configure the baseUrl and paths to load the JavaScript file where the corresponding module is located. The configuration part will be introduced in detail later.

What should be pointed out here is that RequireJS does not guarantee that myFunctionA and myFunctionB must be executed after the page is loaded. When it is necessary to ensure that the script is executed after the page is loaded, RequireJS provides an independent domReady Module, you need to go to the RequireJS official website to download this module, it is not included in RequireJS. With the domReady module, the code in Case 1 can be slightly modified and added with a dependency on domReady.

Case 2: Execute JavaScript after the page is loaded

<script src="./js/require.js"></script> 
  <script> 
 require(["domReady!", "./js/a.js", "./js/b.js"], function() { 
      myFunctionA(); 
      myFunctionB(); 
   }); 
  </script>

After executing the code of Case 2, you can see through Firebug that RequireJS will be inserted into a.js and b.js on the current page respectively. A 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag is declared for asynchronously downloading JavaScript files. The async attribute is currently supported by most browsers, which indicates that the js file in the 27835793f4768f4164d1421d99e293bc tag will not block the download of other page content.

Case 3: RequireJS inserted 3f1c4e4b6b16bbbd69b2ee476dc4f83a

<script type="text/javascript" charset="utf-8" async="" data-requirecontext="_"
data-requiremodule="js/a.js" src="js/a.js"></script>

Use RequireJS to define the JavaScript module

The JavaScript module here is different from the traditional JavaScript code in that it No need to access global variables. The modular design allows JavaScript code to pass these "global variables" as parameters to the implementation body of the module through dependencies when it needs to access "global variables", thus avoiding the need to access or declare global variables in the implementation. Variables or functions, effectively avoiding large and complex namespace management.

As stated in the AMD specification of CommonJS, defining JavaScript modules is achieved through the define method.

Let's first look at a simple example. In this example, by defining a student module and a class module, the student object is created in the main program and the student object is placed in the class.

Case 4: student module, student.js

define(function(){ 
  return { 
   createStudent: function(name, gender){ 
      return { 
        name: name, 
        gender: gender 
      }; 
   } 
  }; 
});

Case 5: class module, class.js

define(function() { 
 var allStudents = []; 
    return { 
      classID: "001", 
      department: "computer", 
      addToClass: function(student) { 
      allStudents.push(student); 
      }, 
      getClassSize: function() { 
      return allStudents.length; 
      } 
    }; 
   } 
 );

Case 6: Main program

require(["js/student", "js/class"], function(student, clz) { 
clz.addToClass(student.createStudent("Jack", "male")); 
clz.addToClass(student.createStudent("Rose", "female")); 
console.log(clz.getClassSize()); // 输出 2 
});

The student module and the class module are both independent modules. Next, we define a new module. This module depends on the student and class modules, so that the logic of the main program part can also be packaged.

Case 7: Manager module that relies on student and class modules, manager.js

define(["js/student", "js/class"], function(student, clz){ 
 return { 
  addNewStudent: function(name, gender){ 
  clz.addToClass(student.createStudent(name, gender)); 
    }, 
  getMyClassSize: function(){ 
  return clz.getClassSize(); 
  } 
   }; 
 });

Case 8: New main program

require(["js/manager"], function(manager) { 
manager.addNewStudent("Jack", "male"); 
manager.addNewStudent("Rose", "female"); 
console.log(manager.getMyClassSize());// 输出 2 
});

Through the above code example, we have Clearly understand how to write a module, how this module is used, and how to define dependencies between modules. There are still some usage tips that need to be reminded:

Try not to provide the module ID. As stated in the AMD specification, this ID is optional. If provided, it will affect the portability of the module in the implementation of RequireJS. , changes in file location will result in the need to manually modify the ID.

Each JavaScript file only defines one module. The search algorithm of module name and file path determines that this method is optimal. Multiple modules and files will be optimized by the optimizer. Avoid the circular dependency of the module. If it cannot be avoided, you can add dependency on the "require" module in the module and configure RequireJS directly in the code with

require(”dependencyModuleName”)

:

前面的介绍中,我们似乎忽略了一个基本问题,模块名字是怎么来的?当我在 require 一个模块时,这个模块是如何映射到具体的 JavaScript 文件上去?这就涉及到如何配置 RequireJS。

最简化的加载 RequireJS 的方式如案例2 所示,在这种情况下,我们没有指定一个 baseUrl 和 paths 给 RequireJS,如果通过如案例10 所示方式,则 data-main 指定了一个在当前 index.html 目录并行的文件夹下的 /js/main.js 作为程序入口,而 /js 目录也将作为 baseUrl 在其他模块定义时候使用。

案例九:载入 require.js

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

因此,我们前面示例中的所有模块依赖,都可以去掉”js/”,直接写 ”student”, ”class”,”manager” 等。 一种更为直接的方式显示指定 baseUrl 和 paths 就是利用 require.config 来设置这些参数。如案例十 所示。

案例十. 配置 RequireJS

<script type="text/javascript" src="./js/require.js"></script> 
<script type="text/javascript"> 
require.config({ 
 baseUrl: "./js", 
 paths: { 
   "some": "some/v1"
 }, 
waitSeconds: 10 
}); 
require( ["some/module", "my/module", "./js/a.js"], 
 function(someModule,  myModule) {} 
); 
</script>

baseUrl指明的是所有模块的 base URL,比如”my/module”所加载的 script实际上就是 /js/my/module.js。注意,以 .js 结尾的文件加载时不会使用该 baseUrl,它们仍然会使用当前 index.html所在的相对路径来加载,所以仍然要加上”./js/”。如果 baseUrl没有指定,那么就会使用 data-main中指定的路径。

paths 中定义的路径是用于替换模块中的路径,如上例中的 some/module 具体的 JavaScript 文件路径是 /js/some/v1/module.js 。 waitSeconds 是指定最多花多长等待时间来加载一个 JavaScript 文件,用户不指定的情况下默认为 7 秒。

另外一个重要的配置是 packages,它可以指定其他符合 CommonJS AMD 规范的目录结构,由此带来了丰富的扩展性。如 Dojo、jQuery 等的模块也可以通过该配置来让 RequireJS 加载。

其他可配置的选项还包括 locale、context、deps、callback等,有兴趣的读者可以在 RequireJS 的官方网站查阅相关文档。

更多使用RequireJS库加载JavaScript模块的实例教程相关文章请关注PHP中文网!

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