JavaScript module, define, require, etc
- 在浏览器里异步加载 JavaScript 文件
- Lazy Load
- 依赖关系管理
JavaScript Module Function
(function () {
var $ = window.jQuery; //-- require jQuery
window.webtk = {}; //-- our module object
}());
Function Expression
(function (name) {
console.log("hello", name);
})("Bob");
define a module
define(['jquery'] , function ($) {
var webtk = {}; //-- our module object
window.webtk = webtk; //-- make it global
return webtk; //-- return it
});
Give it a Name
define("webtk", ["jquery"] , function ($) {
var webtk = {}; //-- our module object
window.webtk = webtk; //-- make it global
return webtk; //-- return it
});
define == require
require(["jquery"], function(){
var webtk = {}; //-- our module object
window.webtk = webtk; //-- make it global
// return webtk; //-- no point to return
});
load from URL
require(["https://path/to/module.js"], function(){
// do something
});
implies an implicit define()
:
define("https://path/to/module.js", ["https://path/to/module.js"], function(){
return
});
And we need a load()
function to do the real job
load(name, deps, src);