【问题标题】:.getScript() callback for multiple usage.getScript() 回调用于多种用途
【发布时间】:2023-03-12 20:58:02
【问题描述】:

如果我有 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()?

【问题讨论】:

  • a.js和b.js是如何加载的?

标签: javascript jquery callback promise


【解决方案1】:

$.getScript() 返回一个 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”中交付的脚本的唯一安全方法是使用分配的 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 失败(或将失败),则错误处理程序将运行。

【讨论】:

    【解决方案2】:

    您可以通过检查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 () { }); 
    

    【讨论】:

    • 如果不是?如何运行somefunction
    • 好的,我正在更新答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2021-08-06
    相关资源
    最近更新 更多