Require.js as a modular programming specification of Javsscript, asynchronous loading module, mainly used in the browser side, the asynchronous loading JS file, so that the browser will not be loaded JS file to lose the response.
First, start
Directory structure:
The first thing to load Require.js
<!-- ***.html - < data-main= "js/app.js" src= "Js/require.js" defer> </script>
App.js is the entry file, we load the math.js inside
App.js
Require ([' App/math '],function(math) { console.log (' 1 + 3 = ', Math.add (1,3));})
Math.js to be written in accordance with AMD specifications
// math.jsdefine (function() { varfunction(A, b ) { return A +b ; } return { add:add }})
You can print the results when you run it.
Ii. loading JS files that do not conform to AMD specifications
Require.js provides us with a shim method to help us load some JS files that do not conform to the AMD specification
First, let's write something in people.js:
// People.js var function (name) { this. Name = name; This function () { console.log (' My name is ${this. name} '); };
Rewrite app.js
// App.js require.config ({ shim:{ ' app/people ': { // Here declare dependent file // Output Method }} ); require ([' App/math ', ' app/people '],function( Math,people) { console.log (' 1 + 3 = ', Math.add (1,3)); var New People (' Jack '); Jack.sayname ();})
Run, correct output:
Iii. BaseURL and Paths
Require provides some ways to help us locate files
Add BaseURL to App.js:
// App.js require.config ({ baseUrl:/// relative to the HTML directory location shim:{ people:{ This declares the dependent file // output Method }} ); require ([' Math ', ' People '],function(math,people) { console.log (' 1 + 3 = ', Math.add (1,3)); var New People (' Jack '); Jack.sayname ();})
You can also output the corresponding results:
We can also specify paths for specific files, for example we want to introduce jquery:
Require.config ({baseUrl:' Js/app ',//location relative to HTML directorypaths:{jquery:‘.. /lib/jquery '//positioning relative to BaseURL}, shim:{people:{deps:[],//this declares the dependent fileExports: ' People '//Output Method}}); Require ([' Math ', ' People ', ' jquery ',function(math,people,$) {$ (function() {Console.log (' 1 + 3 = ', Math.add (1,3)); varJack =NewPeople (' Jack '); Jack.sayname (); })})
The same results are output:
Require.js Basic Use Method record