Questions about jQuery getScript ()

$.getScript("somescript.js", function() { alert('Load Complete'); }); 
  • After loading, is it cached or reloaded if links more than once?
  • If the event depends on the downloaded file, will the event be delayed with an error / timeout if the file takes longer to load or does not load?
  • How can I check and do something if the file fails to load for some reason?

Thanks in advance for your help.

+4
source share
2 answers

1) jQuery queries for scripts via AJAX are never cached unless you specify this as an option in the $ .ajax () function. From the doc:

", Boolean

Default: true, false for dataType 'script' and 'jsonp'

If set to false, this will cause the pages you request to not be cached by the browser.

2) I think I need to see some sample code to understand this part of the question.

3) You cannot do anything if $ .getScript () fails. But you should know that $ .getScript () is just a short version of $ .ajax (), equivilant to:

 $.ajax({ url: url, dataType: 'script', success: function(data) { // } }); 

This means that you can implement the error callback to do something smart if the file does not load, that is:

 $.ajax({ url: url, dataType: 'script', success: function(data) { // }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("panic"); } }); 
+6
source

In addition to Glen's answer, I would like to suggest another option:

 $.getScript({ url: "foo.js", cache: true // or false, depending on your preference. in most cases you would want it true. }).done(function(){ // do something when script was loaded and run }).fail(function(){ // do something when script failed to load }); 

Supported in jQuery 1.12.0 +

+1
source

Source: https://habr.com/ru/post/1307988/


All Articles