Handling errors in jQuery.getScript

前端 未结 6 826
陌清茗
陌清茗 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: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");
    })();
    

提交回复
热议问题