jQuery的getScript()回调是不可靠的还是我做错了什么? [英] Is the callback on jQuery's getScript() unreliable or am I doing something wrong?

查看:321
本文介绍了jQuery的getScript()回调是不可靠的还是我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的脚本来加载另一个脚本:

I'm using the following bit of script to load another one:

$.getScript("CAGScript.js", function () {
    try {
        CAGinit();
    } catch(err) {
        console.log(err);
    }
});

想法是$ .getScript加载脚本,然后在完成后执行回调。 CAGInit()是一个存在于 CAGScript.js 中的函数。

The idea is that $.getScript loads the script, then executes the callback when it's done. CAGInit() is a function that lives in CAGScript.js.

问题是大约一半的时间, CAGInit()不会触发(在任何浏览器中)。登录到Firebug控制台会报告它未定义。剩下的时间它完美运作。

The problem is that roughly half the time, CAGInit() doesn't fire (in any browser). Logging to the Firebug console reports that it's not defined. The rest of the time it works perfectly.

有没有人有任何想法我做错了什么?

Does anyone have any ideas what I'm doing wrong?

谢谢。

推荐答案

如果文件保存在同一个域上,那么jQuery将使用XHR检索其内容,然后全局评估它。这应该工作正常,但如果你遇到问题,那么我建议使用注入脚本标记的替代方法。不幸的是,jQuery没有公开这个功能所以你必须自己做:

If the file is held on the same domain then jQuery will use XHR to retrieve its contents and then will globally "eval" it. This should work fine but if you're having problems then I'd suggest using the alternative method of injecting a script tag. Unfortunately, jQuery doesn't expose this functionality so you'll have to do it yourself:

var script = jQuery('<script/>').attr('src', 'CAGSCript.js').appendTo('head');

var timer = setInterval( function(){ 
    if (window.CAGInit !== undefined) {
        clearInterval(timer);
        script.remove();
        // Do your stuff:
        CAGInit();
    }
}, 200);

最好将其抽象为函数;以上只是一个例子......

It'd be best to abstract this to a function; the above is just an example...

这篇关于jQuery的getScript()回调是不可靠的还是我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆