.getScript() 多次使用回调

.getScript() callback for multiple usage

如果我有 2 个 JS 文件,例如 a.jsb.js

a.js

$.getScript('some.js',function(){
   //Call some function in some.js
});

在文件 b.js 中,我将调用一些函数 some.js,但是如何知道 some.js 已加载 ?

我可以做类似的事情吗..(在b.js

SomejsIsLoaded.then(function(){
   //Call some function in some.js
});

.then() .promise() ?

您可以通过检查some.js中的函数是否存在来检查您的some.js是否存在

if (typeof sumefunction!= 'undefined') {
        //your code
    }

更新: 您应该将此检查放在 DOM 的 .ready() 函数中,如果此检查无效,那么您可以在准备好的函数中手动加载脚本

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = your script location;
head.appendChild(script);

或者您可以继续使用 getScript() 或使用 jQuery .load() 函数作为

$('script').load(function () { }); 

$.getScript() returns 一个 jqXHR 承诺,可以分配以备后用。

你可以写...

var somejsPromise = $.getScript('some.js', function() {
    //Call some function in some.js
});

...但最好不要使用全局命名空间,因此您可以使用 jQuery 命名空间:

$.somejsPromise = $.getScript('some.js', function() {
    //Call some function in some.js
});

如果脚本 'some.js' 没有加载,您还应该包括一些错误处理。至少,记录错误:

$.somejsPromise = $.getScript('some.js', function() {
    //Call some function in some.js
}).then(null, function(error) {
    console.log('getScript(some.js)', error);
});

此后,运行 在 "some.js" 中交付脚本的唯一安全方法是使用分配的承诺的 .then() 方法:

$.somejsPromise.then(function() {
    //Call some function in some.js
}, function() {
    //handle the case that some.js fails to load.
});

如果 some.js 已加载,回调将立即 运行。

如果 some.js 尚未加载,回调将排队,并将 运行 if/when some.js 加载。

如果 some.js 失败(或将会失败),则错误处理程序将 运行。