Handling errors in jQuery.getScript

前端 未结 6 824
陌清茗
陌清茗 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);
    });
    

提交回复
热议问题