Javascript modular tool require JS tutorial

Posted by DataRater on Fri, 21 Jan 2022 14:42:24 +0100

Transferred from: http://www.w3cschool.cc/w3cnote/requirejs-tutorial-1.html, http://www.w3cschool.cc/w3cnote/requirejs-tutorial-2.html

With the gradual enrichment of website functions, the js in the web page has become more and more complex and bloated. The original way of importing js files through script tags can no longer meet the current Internet development mode. We need a series of complex needs such as team cooperation, module reuse, unit testing and so on.

RequireJS is a very compact JavaScript module loading framework and one of the best implementers of AMD specification. The latest version of RequireJS is only 14K after compression, which can be called very lightweight. It can also work with other frameworks at the same time. Using RequireJS will improve the quality of your front-end code.

What are the benefits of requirejs

Official description of requirejs:

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

General meaning:

In the browser, it can be used as a module loader for js files, or in Node and Rhino environments, balabala. This paragraph describes the basic function of requirejs "modular loading". What is modular loading? We will explain them one by one in the following pages

Let's take a look at a common scenario and explain how to use requirejs through examples

Normal writing mode

index.html:

1 2 3 4 5 6 7 8 9 <!DOCTYPE html> <html>     <head>         <script type="text/javascript" src="a.js"></script>     </head>     <body>       <span>body</span>     </body> </html>

a.js:

1 2 3 4 function fun1(){   alert("it works"); } fun1();

Maybe you like it better

1 2 3 4 5 6 7 (function(){     function fun1(){       alert("it works");     }       fun1(); })()

The second method uses block scope to declare function to prevent polluting global variables. The essence is the same. When running the above two examples, I don't know whether you notice that when alert is executed, the html content is blank, that is, < span > body < / span > is not displayed. It appears only after clicking OK. This is the result of JS blocking browser rendering.

requirejs writing method

Of course, first go to the requirejs website to download JS - > requirejs.rog
index.html:

1 2 3 4 5 6 7 8 9 10 11 12 <!DOCTYPE html> <html>     <head>         <script type="text/javascript" src="require.js"></script>         <script type="text/javascript">             require(["a"]);         </script>     </head>     <body>       <span>body</span>     </body> </html>

a.js:

1 2 3 4 5 6 define(function(){     function fun1(){       alert("it works");     }     fun1(); })

 

The browser prompts "it works", which indicates that the operation is correct, but there is a difference. This time, the browser is not blank, and the body has appeared in the page. So far, we can know that requirejs has the following advantages:

  1. Prevent js loading from blocking page rendering
  2. Use program calls to load js to prevent the following ugly scenes
1 2 3 4 5 6 7 8 9 10 <script type="text/javascript" src="a.js"></script> <script type="text/javascript" src="b.js"></script> <script type="text/javascript" src="c.js"></script> <script type="text/javascript" src="d.js"></script> <script type="text/javascript" src="e.js"></script> <script type="text/javascript" src="f.js"></script> <script type="text/javascript" src="g.js"></script> <script type="text/javascript" src="h.js"></script> <script type="text/javascript" src="i.js"></script> <script type="text/javascript" src="j.js"></script>

 

Previous: JS modular tool requirejs tutorial (I): getting to know requirejs We introduced requirejs in a very simple way. This article will talk about some basic knowledge in requirejs, including API usage.

Basic API

Require defines three variables: define, require and requirejs, where require === requirejs. Generally, require is shorter

  • Define from the name, we can see that this api is used to define a module
  • require loads the dependent module and executes the callback function after loading

a.js in the previous article:

1 2 3 4 5 6 7 define(function(){     function fun1(){       alert("it works");     }       fun1(); })

Define a module through the define function, and then use it in the page:

1 require(["js/a"]);

To load the module (note that the dependency in require is an array, even if there is only one dependency, you must use the array to define it). The second parameter of the require API is callback, a function, which is used to process the logic after loading, such as:

1 2 3 require(["js/a"],function(){     alert("load finished"); })

load file

In the previous example, the loading module is local JS, but in most cases, the JS to be loaded on the web page may come from the local server, other websites or CDN, so it cannot be loaded in this way. Let's take loading a jquery library as an example:

1 2 3 4 5 6 7 8 9 10 require.config({     paths : {         "jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery"]       } }) require(["jquery","js/a"],function($){     $(function(){         alert("load finished");      }) })

This involves require config,require.config is used to configure the module loading location. In short, it is to give the module a shorter and better remembered name. For example, mark the address of Baidu's jquery library as jquery, so that the js can be loaded only by writing ["jquery"] when required. We can also configure the local js in this way:

1 2 3 4 5 6 7 8 9 10 11 require.config({     paths : {         "jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery"],         "a" : "js/a"       } }) require(["jquery","a"],function($){     $(function(){         alert("load finished");      }) })

The configuration of paths will refine our module name. Another important function of paths is to configure multiple paths. If the remote cdn library is not loaded successfully, you can load the local library, such as:

1 2 3 4 5 6 7 8 9 10 11 require.config({     paths : {         "jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery", "js/jquery"],         "a" : "js/a"       } }) require(["jquery","a"],function($){     $(function(){         alert("load finished");      }) })

After this configuration, when Baidu's jquery fails to load successfully, it will load the jquery under the local js directory

  1. When using requirejs, there is no need to write when loading the module js suffix, of course, you can't write a suffix
  2. The $parameter found in the callback function in the above example is the output variable of the dependent jquery module. If you depend on multiple modules, you can write multiple parameters in turn:
1 2 3 4 5 require(["jquery","underscore"],function($, _){     $(function(){         _.each([1,2,3],alert);     }) })

If a module does not output variable values, it does not, so try to write the output module in front of it to prevent misunderstanding caused by misplaced position

Global configuration

In the above example, require. Is repeated Config configuration. If you add a configuration to each page, it must be very indecent. requirejs provides a function called "master data". We first create a main js:

1 2 3 4 5 6 require.config({     paths : {         "jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery", "js/jquery"],         "a" : "js/a"       } })

Then use requirejs in the following way in the page:

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

Explain that the data main attribute is added to the script tag of the requirejs script. The js specified by this attribute will be loaded after reuqire js post-processing, we put require After the configuration of config is added to data main, each page can use this configuration, and then the page can directly use require to load all short module names

Data main also has an important function. When the script tag specifies the data main attribute, require will take the js specified by data main as the root path by default. What does it mean? For example, after the above data main = "js / main" setting, after we use require(['jquery ']) (do not configure jQuery paths), require will automatically load js / jQuery js instead of jQuery js, which is equivalent to the default configuration:

1 2 3 require.config({     baseUrl : "js" })

Third party module

Modules loaded through require generally need to comply with AMD specifications, that is, define is used to declare modules, but sometimes js of non amd specifications need to be loaded. At this time, another function needs to be used: shim. Shim is difficult to explain. Shim is directly translated into "pad". In fact, it also has this meaning. At present, I mainly use it in two places
1. Non amd module output, which "pads" non-standard amd modules into usable modules. For example, in the old version of jquery, there is no inheritance from AMD specification, so you cannot directly require["jquery"]. At this time, shim is required. For example, if I use the underscore class library, but it does not implement amd specification, we can configure it like this

1 2 3 4 5 6 7 require.config({     shim: {         "underscore" : {             exports : "_";         }     } })

After this configuration, we can reference the underscore module in other modules:

1 2 3 require(["underscore"], function(_){     _.each([1,2,3], alert); })

For non amd modules in the form of plug-ins, we often use jquery plug-ins, and these plug-ins basically do not comply with AMD specifications, such as jquery Form plug-in, you need to "pad" the form plug-in into jquery:

1 2 3 4 5 6 7 8 9 10 require.config({     shim: {         "underscore" : {             exports : "_";         },         "jquery.form" : {             deps : ["jquery"]         }     } })

It can also be abbreviated as:

1 2 3 4 5 6 7 8 require.config({     shim: {         "underscore" : {             exports : "_";         },         "jquery.form" : ["jquery"]     } })

After this configuration, we can use jquery after loading the plug-in

1 2 3 4 5 require.config(["jquery", "jquery.form"], function($){     $(function(){         $("#form").ajaxSubmit({...});     }) })

Well, this is the basic configuration of requirejs, and some extended functions will be mentioned later

Source: https://github.com/liuxey/blog/issues/2

 

Topics: Front-end