在写arcgis api的时候总是要require导入模块,下去专门看了一下这个到底是怎么回事,查了一点资料.
模块类似于java中的包,说白了就是导包,js里面导入的就是js文件,再直白一点,就是写个脚本,在页面添加script标签,从而实现了导入js脚本,在页面就能够使用导入进来的脚本了.
步骤:
- 准备三个js文件:
module1.js:
console.log("module1");
module2.js:
console.log("module2");
module3.js:
console.log("module3");
- 实现加载js文件模块
//实现一个自定的require加载模块
function myRequire(deps, callback) {
//记录模块加载数量
var ready = 0;
//创建脚本标签
function load(url) {
var script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = url;
return script;
}
var nodes = [];//存储script标签对象
for (var i = deps.length - 1; i >= 0; i--) {
nodes.push(load(deps[i]));
}
console.log(nodes);
//加载script脚本
for (var j = nodes.length-1; j >= 0; j--) {
// 倒序加载
nodes[j].addEventListener("load", function (event) {
ready++;
// console.log(ready);
//如果所有依赖脚本加载完成,则执行回调函数
if (ready === nodes.length) {
callback();
}
},false);
document.head.appendChild(nodes[j]);
}
}
- 测试:
myRequire(["module1.js","module2.js","module3.js"],function () {
console.log("ready!");
});