Is the callback on jQuery's getScript() unreliable or am I doing something wrong?

后端 未结 11 1243
Happy的楠姐
Happy的楠姐 2020-12-03 03:17

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

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


        
相关标签:
11条回答
  • 2020-12-03 03:54

    I've gotten bit by this issue on Chrome as well. jQuery occasionally calls the success callback as if all is well, but the script hasn't actually been loaded properly. In our case, the solution was to simply change from trusting jQuery:

    <script>
        $.getScript("helpers.js", function () {
            // use helpers....or: EXPLODE (wheeeee!)
            helpers.doSomething();
        });
    </script>
    

    To trusting the browser:

    <script src="helpers.js"></script>
    <script>
        helpers.doSomething();
    </script>
    

    I'm finding again and again that "less jQuery == less edge cases == less bugs". And usually more readable code, too!

    0 讨论(0)
  • 2020-12-03 03:57

    I think you can start by checking testStatus of the callback function to make sure that the script was really loaded. Callback function has two parameters, more defails on those you can find on jQuery Docs

    $.getScript("CAGScript.js", function (data, textStatus) {
        if (textStatus === "success") {
            try {
                CAGinit();
            } catch(err) {
                console.log(err);
            }
        } else {
            console.log("script not loaded");
        }
    });
    
    0 讨论(0)
  • 2020-12-03 03:57

    My way is

    setTimeout(function(){ 
      $.getScript( "CAGScript.js");
      }, 
    2000);
    

    this same issue we face in angular also when we want to update data in $scope and it is solved by using $timeout in same manner in angular...

    0 讨论(0)
  • 2020-12-03 03:59

    Just wanted to offer some insight I have on this issue. The callback won't fire if there is an error in the code you are loading and (at least on Chrome with jQuery 1.7.1) the error will be swallowed. I discovered that I had a stray curly brace from autocomplete in the code I was loading and the callback function didn't fire. Intermittent behavior here could be caused by changing the loaded code between tests.

    0 讨论(0)
  • 2020-12-03 04:00

    Just had the same problem on firefox, solved it with a little hack.

    Applying it to your example:

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

    Basically forcing an evaluation of the XHR response if it fails to do so by itself.

    0 讨论(0)
提交回复
热议问题