Handling errors in jQuery.getScript

前端 未结 6 805
陌清茗
陌清茗 2021-01-02 14:00

jQuery\'s getScript function doesn\'t seem to support an error callback function. I can\'t use the global ajax error handling code here, a local error function would be idea

相关标签:
6条回答
  • 2021-01-02 14:03

    For cross domain script tags, the success event fires but the error event does not; no matter what syntax you use. You can try this approach:

    1. Create an error handler and set it to fire after few seconds using handle = window.setTimeout
    2. Inside your success callback function, cancel the timeout using window.clearTimeout(handle)

    Sample code:

    var timeoutId; // timeout id is a global variable
    timeoutId = window.setTimeout(function() {
        alert("Error");
    }, 5000);
    $.getScript("http://other-domain.com/script.js", function(){
        window.clearTimeout(timeoutId);
    });
    
    0 讨论(0)
  • 2021-01-02 14:13

    This is a bit of a hack, but..

    You could declare a variable inside the scripts you load and check for it after you've loaded a script (assuming that the complete-function still fires):

    script_test.js:

    var script_test = true;
    

    And then:

    $.getScript("script_test.js", function ()
    {
        if (typeof script_test !== undefined) alert("script has been loaded!");
    });
    

    Or you could just try and see if whatever is in your script, actually exists--functions, variables, objects, etc.


    A more generic way to do this would be adding a self-executing function inside the scripts you want to load, and make them execute a function in your "main" script:

    main_script.js:

    function scriptLoaded(scriptName)
    {
        alert(scriptName + " loaded!");
    }
    
    $.getScript("script_test.js");
    

    script_test.js:

    (function ()
    {
        scriptLoaded("script_test.js");
    })();
    
    0 讨论(0)
  • 2021-01-02 14:14

    Unless you don't use jQuery 2.0+ $.getScript seem to be the wrong choice, because it does not provide any error handling capabilities while making cross-domain requests. None of those: fail, complete, error, statusCode will work. I've checked it with jQuery 1.11.2
    Solution with setTimeout will be too slow if you have to load fallback script when the first will fail.
    In this case script.onerror callback seem to be the cleanest way.

    var script = document.createElement('script');
    document.head.appendChild(script);
    script.onload = function () {
        // loaded
    };
    script.onerror = function () {
        // failed
    };
    script.src = 'https://example.com/main.js';
    

    In combination with $.Deferrred provides reliable way to build complex loaders.

    var libLoaded = $.Deferred();
    var script = document.createElement('script');
    document.head.appendChild(script);
    script.onload = libLoaded.resolve;
    script.onerror = function () {
        // load fallback script, no error handling
        $.getScript('/fallbackLib.js')
            .done(libLoaded.resolve)
    };
    script.src = 'https://example.com/lib.js';
    
    $.when(libLoaded).then(
        // fanally I can use my lib safly
    );
    
    0 讨论(0)
  • 2021-01-02 14:16

    As of jQuery 1.5 you can append a .fail to your call to getScript.

    $.getScript('foo.js', function(){
        //script loaded and parsed
    }).fail(function(){
        if(arguments[0].readyState==0){
            //script failed to load
        }else{
            //script loaded but failed to parse
            alert(arguments[2].toString());
        }
    })
    

    http://api.jquery.com/jQuery.getScript/#handling-errors

    0 讨论(0)
  • 2021-01-02 14:23

    jquery.ajax has a alternative way to handle error

    jQuery.ajax({
            type: "GET",
            url: 'http://www.example.com/script_test.js',
            dataType: "script",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log('error ', errorThrown);
            },
            success:function(){
                console.log('success');
            }
        });
    
    0 讨论(0)
  • 2021-01-02 14:24

    The global JQuery Ajax-ErrorHandler will work!

    Prior to the $.getScript-Call setup the Error Handler to cach the error.

    $(document).ajaxError(function(e, xhr, settings, exception) {
        alert('error in: ' + settings.url + ' \n'+'error:\n' + exception );
    });
    

    As described in the JQuery manual: http://api.jquery.com/ajaxError/.

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