Handling 404s while loading cached scripts using j

2019-07-25 04:20发布

I want to load a JS file using jQuery (for reasons out of scope of this post). I would like the cache to be used if available. Also I cannot set the global ajax cache setting to true (again for reasons out of scope). This rules out my using the getScript method So, per jQuery's website I did the following:

$(function() {

  options = {
    dataType: "script",
    cache: true,
    // scheme-less URI.
    url: "//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min1.js",//<--- 404
    success: function() {
      console.log("yes")
    },
    error: function() {
      console.log("error")
    },
    always: function() {
      console.log("always")
    },
    statusCode: {
      404: function() {
       console.log("404")
        }
    }
  };
  var $d = jQuery.ajax(options);  
});

Now this works well in all cases except when the script request returns a 404, none of the error or fail methods get called.

I can force it to get called by applying a timeout , but I dont want to. Why are the error handling methods not getting called?

Fiddle: https://jsfiddle.net/15kozdpf/4/

2条回答
forever°为你锁心
2楼-- · 2019-07-25 04:57

Try adding https: before the URL. It works for me

**Fiddle:** https://jsfiddle.net/15kozdpf/3/
查看更多
霸刀☆藐视天下
3楼-- · 2019-07-25 05:09

Seems like a bug in jQuery 1.

If you remove the dataType: "script", everything works (regardless the URL you request).

Another option - upgdate to jQuery 2:
https://jsfiddle.net/6asrte12/

查看更多
登录 后发表回答