Jquery getScript caching

前端 未结 6 940
花落未央
花落未央 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条回答
  •  盖世英雄少女心
    2020-12-02 20:56

    By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested.

    jQuery doc site has a nice extension for not appending a timestamp to the request and bypass the cache:

    jQuery.cachedScript = function( url, options ) {
    
      // Allow user to set any option except for dataType, cache, and url
      options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
      });
    
    
      // Use $.ajax() since it is more flexible than $.getScript
      // Return the jqXHR object so we can chain callbacks
      return jQuery.ajax( options );
    };
    
    // Usage
    $.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
      console.log( textStatus );
    });
    

    Source

提交回复
热议问题