james emanon
james emanon

Reputation: 11807

Is there any way to cancel/stop/abort a getScript call?

So, I've been looking about and there doesn't appear to be a way to actually abort/cancel/stop a script call once its made.

I find having to use lazy load to address a non-responsive script call to a third party kinda odd. With json/ajax, sure I can just timeout on it - great. But with a script call, no such luck. I figured jQuerys $.getScript would allow for such behavior. no?

What I am hoping to accomplish: cancel a blocking js call.

couldn't something like this work?

var getScript = $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
     //
});

var exitOut = setTimeout(function(){
    getScript.abort();
},2000)

from what I've been reading a "script" request cannot be abort mid-stride.

BUT, since getScript is just an ajax call, I was hoping that timeout could also apply here. But some of my tests aren't bearing that out?

Any other solutions besides lazy loading?

Upvotes: 7

Views: 1314

Answers (1)

Bergi
Bergi

Reputation: 664395

BUT, since getScript is just an ajax call, I was hoping that timeout could also apply here.

Actually, getScript does not use XHR but a <script> element. Therefore, abort does not work and the timeout ajax option does neither.

You might be better off with loading the script via XHR and then manually evaling it:

$.ajax({
    url: "ajax/test.js",
    dataType: "text",
    timeout: 2000
}).done(function(str) {
    $.globalEval(str);
});

Upvotes: 6

Related Questions