.getScript()回调用于多种用途

.getScript() callback for multiple usage

本文关键字:用于 回调 getScript      更新时间:2023-09-26

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

a.js

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

在文件b.js中,我将调用函数somesome.js,但如何知道萨默.js

我能做点什么吗。。(在b.js中(

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

.then() .promise()

$.getScript()返回一个jqXHR promise,该promise可以分配给以后使用。

你可以写。。。

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"中交付的脚本的唯一安全方法是使用指定promise的.then()方法:

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

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

如果some.js尚未加载,则回调将排队,并在some.js加载时运行。

如果some.js已经失败(或将要失败(,那么错误处理程序将运行。

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

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

更新:你应该把这张支票放在。DOMready()函数,如果此检查无效,则可以在准备好的函数中手动加载脚本

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 () { });