<script src= "Js/require.js" ></script>
<script src= "Js/require.js" data-main= "Js/main" ></script>
Require ([' jquery ', ' underscore ', ' backbone '), function ($, _, backbone) {
Some code here
});
Using the Require.config () method, we can customize the load behavior of the module. Require.config () is written on the head of the main module (main.js). A parameter is an object that specifies the load path for each module by the paths property of the object.
Require.config ({
Paths: {
"jquery": "Jquery.min",
"Underscore": "Underscore.min",
"Backbone": "Backbone.min"
}
});
Require.config ({
BASEURL: "Js/lib",
Paths: {
"jquery": "Jquery.min",
"Underscore": "Underscore.min",
"Backbone": "Backbone.min"
}
});
Require.config ({
Paths: {
"jquery": "Https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min"
}
});
Suppose you now have a math.js file that defines a math module. Well, Math.js is going to write this:
Math.js
Define (function () {
var add = function (x, y) {
return x+y;
};
return {
Add:add
};
});
The loading method is as follows:
Main.js
Require ([' math '], function (math) {
Alert (Math.add ());
});
If the module also relies on other modules, then the first parameter of the Define () function must be an array that indicates the dependency of the module.
define ([' mylib '], function (mylib) {
function foo () {
Mylib.dosomething ();
}
return {
Foo:foo
};
});
When the require () function loads the above module, the Mylib.js file is loaded first.
Simple use of require.js