1

I am asynchronously loading scripts through LabJS and have a chain of dependent scripts. Now if one of the scripts in the chain breaks (in the sense that it can not be downloaded, or connection times out) I believe that the remaining scripts under the dependency chain will not be executed. In such an event, is it possible to provide a custom callback function to take appropriate measures if a particular script fails to load ? If this is not possible with LabJS, is it possible with any other Asynchronous script loader ?

lorefnon
  • 12,875
  • 6
  • 61
  • 93

3 Answers3

4

Here's an example showing how to wrap setTimeout() timeouts around LABjs code... in this case it provides a fallback mechanism where it tries to load jquery from a CDN, then if the timeout passes, it aborts that and tries to load jquery from a local file instead.

https://gist.github.com/670840

Kyle Simpson
  • 15,725
  • 2
  • 33
  • 55
  • Thank you. Its really awesome to have received the answer straight from you :D – lorefnon Jun 24 '11 at 17:32
  • @Kyle can you kindly show an example of how to integrate that into an existing LABjs loading chain? Thanks! – fortuneRice Jan 04 '12 at 17:38
  • @fortuneRice you wouldn't really integrate it into an existing chain... this approach would basically constitute its own separate chain, and/or replace the existing chain. – Kyle Simpson Feb 16 '12 at 20:55
2

According to getify, who happens to be sitting about 20 feet away from me, there's not a way to handle timeouts like that in general, mostly because a timeout is not an explicit, "positive" event. (In the specific case of how the library handles the dependency chain in such cases, I'll let the author himself clarify.)

What you can do is use your own watchdog to wait as long as you feel is appropriate. Just run an interval timer, checking for some tell-tale sign that your script has made it onto the page, and if after some number of iterations you fail to see it you can fall back on an alternative (different script host, whatever).

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

What about this? I have not tested this:

$LAB.script('jquery-from-cdn.js').wait(function(){

    if(!window.jQuery) {
        $LAB.script('local-jquery.js').wait(load_scripts);
    } else {
        load_scripts();
    }

});

function load_scripts() {
    $LAB.script('other-js.js');
}
Martti Laine
  • 12,655
  • 22
  • 68
  • 102
  • Hmm, I haven't tested this with a timeout, but with a 404 the wait callback isn't even fired in FF/Chrome. Another problem is that you would lose the ability to download js files in parallel, a key feature of LABjs. Jquery would have to be downloaded and parsed before any of the other scripts are downloaded. – JoeyP Jun 21 '12 at 19:46