Questions about jQuery's getScript()

天大地大妈咪最大 提交于 2019-12-10 17:27:45

问题


$.getScript("somescript.js", function() {
    alert('Load Complete');
});
  1. Once loaded, is it cached or is it loaded again if referenced more than once?
  2. If an event depends on this file being loaded, will the event be delayed of fail/timeout in case the file takes longer to load or doesn't load?
  3. How do I check and do something in case the file fails to load for some reason?

Thanks in advance for your help.


回答1:


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

"cache, Boolean

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

If set to false it will force the pages that you request to not be cached by the browser."

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

3) You can't do anything if $.getScript() fails. But, you should be aware that $.getScript() is just a short-hand 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 clever if the file fails to load, ie:

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



回答2:


In addition to Glen's answer I would like to offer 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 on jQuery 1.12.0+



来源:https://stackoverflow.com/questions/2711443/questions-about-jquerys-getscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!