1: What is
①: It is a js script loader, which follows the AMD (Asynchronous Module Definition) specification, implements asynchronous loading of js scripts, does not block the rendering of pages and the execution of subsequent scripts, and provides the function of executing corresponding callback functions after loading is completed;
②: It is required that js scripts must be modular, that is, filed; and one of its functions is to load js modules, that is, js files.
③: You can manage the dependencies between js modules/files; that is, different frameworks such as Jquery, AngularJs, etc. adopt different syntaxes, and js files using these syntax must be ranked or later when importing to be successfully executed, which can solve the sort dependency problem.
2: Why use it
①: When loading, the browser will stop rendering of the web page, for the following reasons:
When not in use, the file is written as follows:
<!DOCTYPE html> <html> <head> <script type="text/javascript" src=""></script> </head> <body> <span>Hellow World</span> </body> </html>
In the imported file:
(function(){ function fun1(){ alert("JS file has taken effect"); } fun1(); })()
When running the above code, we can notice that when the prompt box popped up by alert appears, the part of the web page html is still blank and no content is displayed. When we click OK, "Hellow World" will be displayed on the web page. This is the result of JS blocking the browser rendering. The more files are loaded, the longer the web page will lose response.
②: Since there is a dependency between js files, the loading order must be strictly guaranteed. The module with the largest dependency must be loaded at the end. When the dependency relationship is very complicated, the code writing and maintenance will become difficult. For example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script type="text/javascript" src="js/jquery-1.10." ></script> <script type="text/javascript" src="js/" ></script> </head> <body> <div style="width: 100px;height: 100px;background-color: red;"></div> </body> </html>
In the file
$(function(){ $("#div1").css("background-color","blue"); })
In order for the code in it to take effect, you must put the <script type="text/javascript" src="js/" >/script> line of code behind <script type="text/javascript" src="js/jquery-1.10." >>. In this way, when there are many frameworks and js files used, their import order will become very troublesome.
The birth of this is to solve the two problems mentioned above:
1. Implement asynchronous loading of js files to prevent web pages from losing response;
2. Manage the dependencies between modules to facilitate code writing and maintenance.
Three: Loading
①: First of all, we need to go to the official website to download the latest version, the official website:/docs/
After the download is completed, put it in the js subfolder of the website project and it can be used:
<script src="js/"></script>
You may encounter a problem here: loading this file may also cause the web page to lose response. There are two solutions to this problem:
1. Write this line of code into the following format:
<script src="js/" defer async="true" ></script>
Among them: the async attribute and the defer attribute indicate that the file needs to be loaded asynchronously to prevent the web page from losing response. IE only supports the defer attribute, not the async attribute.
2. Place the file at the bottom of the web page to load.
②: After loading, we can load our own code. Assuming that our own js file is named and placed in the js folder, then we only need to execute the following code:
<script src="js/" data-main="js/main"></script>
In the above code, the function of the data-main attribute is to specify the main module of the web program. That is, the file under the js directory will be loaded first. Since the default file suffix name is js, you can omit ".js" abbreviated as main.
Four: Basic API
In the previous section, we introduced the document, which is written:
define(function(){ function fun1(){ alert("Effective"); } fun1(); })
In this way, we define a module through the define function, and then use the require() function defined in the page through the AMD specification:
require(["js/main"]);
Generally speaking, it will rely on other js frameworks, such as jquery, etc., so we will now be in the page file. We need to write in the following format:
require(['A', 'B', 'C'], function (A, B, C){ // js code});
The require() function accepts two parameters. The first parameter is an array, representing the framework to which it depends. The above example is ['A', 'B', 'C'], that is, the code in it needs to use these three modules; the second parameter is a callback function, and after all the currently specified modules are loaded successfully, it will be called. The loaded module will be passed in the function as a parameter, so that these modules can be used inside the callback function.
require() will load the three modules A, B, and C asynchronously, and the browser will not lose its response; the callback function it specifies will only run after the previous modules are successfully loaded, solving the dependency problem.
under. Let's take jquery as an example to illustrate how this function runs:
require(['jquery'], function ($){ // jquery code});
jQuery will be loaded first, and then the callback function will be run. The code of , is written in the callback function. Note: The dependency in requires is an array, and even if there is only one dependency, you must use an array to define it.
Five: Load the file
In the previous section, the dependency module is ['jquery']. By default, it is assumed that the module is in the same directory, the file name is , and then it is automatically loaded. In addition, we can customize the loading behavior of the module through the() method. () is written at the head of the (, and its parameter is an object, and the paths attribute of this object specifies the loading path of each module.
({ paths: { "jquery": "", "anjular": "" } });
The above module path is in the same directory (js subdirectory). If these modules are in other directories, such as the js/lib directory, there are two ways to write them. One is to specify the path one by one:
({ paths: { "jquery": "lib/", "anjular": "lib/" } });
The other is to directly change the root directory (baseUrl):
({ baseUrl: "js/lib", paths: { "jquery": "", "anjular": "" } });
In the previous examples, the loading modules were all local js, but in most cases, the JS that web pages need to load may come from local servers, other websites or CDNs, so this way cannot be loaded. Let's take loading a jquery library as an example:
({ paths : { "jquery" : ["/jquery/2.0.3/jquery"] } })
The configuration appears repeatedly in the example above. If configuration is added to each page, it will inevitably be very troublesome. Requirejs provides a function called "master data". We can put all the configurations in and call it in the page.
<script data-main="js/main" src="js/"></script>
This configuration can be used for each page, and then the page can directly use require to load all short module names.
6: How to write AMD module
The loaded module adopts the AMD specification, that is, the module must be written in accordance with the AMD regulations. Specifically, the module must be defined using a specific define() function. If a module does not rely on other modules, it can be defined directly in the define() function. Suppose there is now a file that defines a math module. Then, just write it like this:
define(function (){ var add = function (x,y){ return x+y; }; return { add: add }; });
Then in the page:
require(['math'], function (math){ alert((1,1)); });
If this js file also depends on other modules, then the first parameter of the define() function must be an array that indicates the dependency of the module.
define(['jquery'], function($){ $("#div1").css("background-color","red"); })
When the require() function loads the above module, the file will be loaded first.
Seven: Third-party module
Modules loaded through require generally need to comply with AMD specifications, that is, use define to declare modules, but in some cases, non-AMD specifications need to be loaded. At this time, another function needs to be used: shim:
1. Non-AMD module output, turning non-standard AMD module into available modules. For example: in the old version of jquery, the AMD specification is not inherited, so you cannot directly require ["jquery"], and you need shim
({ shim: { "jquery" : {exports : "$"} } })
After this configuration, we can refer to the jquery module in other modules:
require(["jquery"], function(_){ $("#div1").css("background-color","red"); })
2. For non-AMD modules in plug-in form, we often use jquery plug-ins, and these plug-ins basically do not comply with AMD specifications. For example, plug-ins, you need to add form plug-ins to jquery:
({ shim: { "" : { deps : ["jquery"] } } }) (["jquery", ""], function($){ $(function(){ $("#form").ajaxSubmit({...}); }) })
The above is a detailed explanation of the basic usage of require. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!