Jquery getScript caching

前端 未结 6 942
花落未央
花落未央 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 21:05

    First lets clarify what is means that the jQuery disables the caching.

    When jQuery disables the cache is means that is force the file to be load it again by the browser with some kind of trick, eg by adding one extra random number as parameter at the end of the url.

    When jQuery have enable the cache, is not force anything and let the cache that you have set on the header of this file. Which means that if you do not have set on the header of the files parameters to keep it on browser cache, the browser will try to load it again by some methods.

    So with enable the cache by jQuery you must also have been set the correct cache headers on your static files to be keep on browser cache, or else browser may try to load them again.

    For files that browser see the created date on header, then is connect to the server asking the header again, is compare it and if is not have change then is not load it again, but is make one call to the server.

    For files that you have set the a max age, and not ask the server till that date, then the browser is direct load it from the cache if he finds it.

    To summarize:
    The cache:true is let the browser decide for the cache of this file from the header you send.
    The cache:false is force the file to be load again.

    Some relative to cache questions:
    caching JavaScript files
    IIS7 Cache-Control

    Tthe inside code
    The getScript() is calling the jQuery.get() witch is a shorthand Ajax function of

    $.ajax({
      url: url,
      data: data,
      success: success,
      dataType: dataType
    });
    

    So by calling the getScript() you make an ajax call, and the jQuery did not keep any kind of cache of your files if this is what you think at the first place.

    Custom function to load the sripts
    If you do not won to make a global cache:true, and you need only some files to be loaded with cache:true, you can make a custom function as:

    function getScriptCcd(url, callback)
    {
        jQuery.ajax({
                type: "GET",
                url: url,
                success: callback,
                dataType: "script",
                cache: true
        });
    };
    

    This is not affected by the global cache parameter and is load the script files with out adding anything non-cache parameters at the end.

提交回复
热议问题