Jquery getScript caching

前端 未结 6 930
花落未央
花落未央 2020-12-02 20:48

By Default $.getScript() disables caching and you can use $.ajaxSetup and set caching to true. When testing if the script is actually cached with Firebug most of the time t

6条回答
  •  萌比男神i
    2020-12-02 20:56

    What do you perhaps are looking for is a getScriptOnce function, which basically, if it knows that the file was already loaded successfully, does not load again such file when such function is called.

    I wrote such function. You can test with the Network tab in Firebug or Chrome dev tools. This just loads the same file once. You just need to copy to your files the getScriptOnce function and the global array ScriptArray

    var getScriptOnce = (function(url, callback) {
      var scriptArray = []; //array of urls
      return function (url, callback) {
          //the array doesn't have such url
          if (scriptArray.indexOf(url) === -1){
              if (typeof callback === 'function') {
                  return $.getScript(url, function(script, textStatus, jqXHR) {
                      scriptArray.push(url);
                      callback(script, textStatus, jqXHR);
                  });
              } else {
                  return $.getScript(url, function(){
                      scriptArray.push(url);
                  });
              }
          }
          //the file is already there, it does nothing
          //to support as of jQuery 1.5 methods .done().fail()
          else{
              return {
                  done: function () {
                      return {
                          fail: function () {}
                      };
                  }
              };
          }
      }
    }());
    
    /*#####################################################################*/
    /*#####################################################################*/
    
    
    //TEST - tries to load the same jQuery file twice
    var jQueryURL = "https://code.jquery.com/jquery-3.2.1.js";
    console.log("Tries to load #1");
    getScriptOnce(jQueryURL, function(){
      console.log("Loaded successfully #1")
    });
    
    //waits 2 seconds and tries to load again
    window.setTimeout(function(){
      console.log("Tries to load #2");
      getScriptOnce(jQueryURL, function(){
        console.log("Loaded successfully #2");
      });
    }, 2000);

提交回复
热议问题