Require.js/AMD Modular Loading
Developers want to use script loaders to make chaotic rich script applications more orderly, and Require .js is one such option. Require.js is a powerful toolkit that automatically works with AMD technology to smooth out even the most complex script dependency graphs.
Now let’s look at a simple script loading example using the function of the same name in Require.js.
require(['moment'], function(moment) {
console.log(moment().format('dddd')); // 星期几
});
Copy after login
require function accepts an array of module names and loads all these script modules in parallel. Unlike yepnope, Require.js does not guarantee that the target scripts are run in order, but only ensures that their running order can meet their respective dependency requirements, but only if the definition of these scripts complies with AMD (Asynchronous Module Definition, asynchronous module definition) specifications.
Case 1: Loading JavaScript files
<script src="./js/require.js"></script>
<script>
require(["./js/a.js", "./js/b.js"], function() {
myFunctionA();
myFunctionB();
});
</script>
Copy after login
As shown in Case 1, there are two JavaScript files a. js and b.js respectively define two methods myFunctionA and myFunctionB. You can use RequireJS to load these two files in the following way. The code in the function part can reference the methods in these two files.
The string array parameter in the require method can allow different values. When the string ends with ".js", or starts with "/", or is a URL, RequireJS will It is considered 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 load the JavaScript where the corresponding module is located based on the baseUrl and paths configured by the user. document. The configuration part will be introduced in detail later.
It should be pointed out here that RequireJS does not guarantee that myFunctionA and myFunctionB must be executed after the page is loaded by default. When there is a need to ensure that the script is executed after the page is loaded, RequireJS provides a For the 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>
Copy after login
Execution case After the second code, you can see through Firebug that RequireJS will insert a
Latest Articles by Author
-
2023-03-07 21:36:01
-
1970-01-01 08:00:00
-
1970-01-01 08:00:00
-
2023-03-11 13:22:01
-
1970-01-01 08:00:00
-
2023-03-11 15:08:02
-
2023-03-12 07:44:02
-
2023-03-11 10:18:01
-
1970-01-01 08:00:00
-
1970-01-01 08:00:00