作者:手机用户2502907453 | 来源:互联网 | 2023-02-03 16:39
我正在尝试从书签中加载JS文件.JS文件有这个包装模块的JS:
(function (root, factory) {
if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else {
// Browser globals
root.moduleGlobal = factory();
}
}(this, function factory() {
// module script is in here
return moduleGlobal;
}));
因此,如果网页使用RequireJS,则脚本在加载时不会导出全局.为了解决这个问题我暂时设置define
到null
,加载脚本,然后重置define
为其原始值:
function loadScript(url, cb) {
var s = document.createElement('script');
s.src = url;
s.defer = true;
var avoidRequireJS = typeof define === 'function' && define.amd;
if (avoidRequireJS) {
var defineTmp = define;
define = null;
}
s.Onload= function() {
if (avoidRequireJS) define = defineTmp;
cb();
};
document.body.appendChild(s);
}
这是有效的,但在我看来,当应用程序的其他部分可能依赖于它时,更改全局变量可能会有问题.有没有更好的方法来解决这个问题?