开发者

Set timeout on third-party file request with jQuery

I'm trying to integrate a script file hosted by a third party into a new web site.

Currently, I'm adding a SCRIPT tag to the DOM for that third-party script file on document ready:

$(document).ready( function() {

    var extScript = document.createElement('script');
        extScript.type = 'text/javascript';
        extScript.src = 'http://third-party.com/scriptfile.js';

    $('head').append(extScript);

});

function extScriptCallback() {
    $('#extWidgetContainer').show();
}

But sometimes that third-party script file request times out or takes a long time to respond.

So, for the sake of best practice, I want to provide alternative content if the external script takes longer than e.g. 10 seconds to l开发者_如何学Coad.

How do I achieve this? I've looked at JavaScript's native setTimeout(), as well as jQuery's delay() function, but I'm not sure which I should use--or how.

Grateful for any suggestions.


There are a couple of ways you can approach this. The first method would be to check on a timer for the existence of a function or variable provided by the third party script. If it's not available when you check for it, it's not loaded yet:

$(document).ready( function() {  
    var extScript = document.createElement('script');
        extScript.type = 'text/javascript';
        extScript.src = 'http://third-party.com/scriptfile.js';

    window.setTimeout(function ()
    {
        if ("thirdPartyFuncName" in window)
            alert("loaded");
        else
            alert("Not loaded yet");
    }, 10000); // 10 secs

    $('head').append(extScript);
}); 

The other way you could go is to investigate the onload and onreadystatechange events provided by browsers. AFAIK, onload is widely implemented, so you could do something like this:

var timer;
extScript.onload = function () { clearTimeout(timer); }
timer = window.setTimeout(function ()
{
    alert("not loaded");
}, 10000); // 10 secs

The downside to this approach is that the load event will fire even if the script has a syntax error, so I still think the first approach is your best bet, because it checks for functionality existence.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜