我正在尝试创建一个可以异步加载(AMD)并通过 HTML 脚本标记加载的模块。我将此构造添加到我的模块中(我从 jQuery 源代码中获取它):
if ( typeof define === "function" && define.amd ) {
define( "mymodule", ['googlemaps'], function(google) {
return myModule;
});
}
myModule = function() {
// here code uses "google"
}
我的模块依赖于 Google Maps API,因此如果我通过 HTML 脚本标记加载我的模块,它就可以工作。但是,如果我的模块是异步加载的,则变量“google”仅在“define” block 中可用。有什么方法可以将此变量传递到全局范围(对于我的模块文件)?
最佳答案
(function(global, factory) {
if (typeof define === 'function' && define.amd) { // requirejs
return define(['googlemaps'], factory);
} else if (typeof exports === 'object') { // nodejs
return module.exports = factory(require('googlemaps'));
} else { // html
return global['Odysseus'] = factory(global['googlemaps']);
}
})(this, function(GoogleAPI) {
...
return myModule;
});
关于javascript - RequireJS - 自己的模块,有两种加载方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25301810/