[Solved] How does jQuery disable AJAX caching?

To disable caching files from ajax requests, you can use jQuery’s

$.ajaxSetup({
    cache: false
});

But how does jQuery do this? I know jQuery is a javascript library, so whatever can be done with jQuery can be done with plain javascript. So my question is: What is the javascript code that jQuery uses under the hood to turn off ajax file caching?

Enquirer: Kyle Lin

||

Solution #1:

This is the source of the cache

        if ( s.cache === false ) {
            s.url = rts.test( cacheURL ) ?

                // If there is already a '_' parameter, set its value
                cacheURL.replace( rts, "$1_=" + nonce++ ) :

                // Otherwise add one to the end
                cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
        }

s is ajax’s option,
If you set cache false, It will add a search to you request url,
The ‘nonce’ is jQuery.now(), It’s a time;
So browser will not user cache when you send ajax , request url always differenrt.

Respondent: Vimo

Solution #2:

I think that Today’s Browsers use onunload = function(){} just like that (yes, exactly) to prevent the Browser from caching a web page, as it was when you left it to go to another page.

It’s important to under stand, however, that that is not the same as the Browser’s ability to remember the JavaScript loaded from your <script type="text/javascript" src="https://www.py4u.net/discuss/somePage.js"></script> tags when they have that src attribute. If you change your JavaScript on a live site, you’ll want to change the name of that file, or, if the Client has not cleared their cache their Browser will attempt to load the file as it remembers it.

Respondent: StackSlave

Solution #3:

The easiest way to shut off browser caching of Ajax requests is with a query string parameter based on time.

var t = new Date().getTime();

console.log('some-url?_='+t);

This yields the following query string

?_=1481683928873

The browser will see this as a different request (assuming it only makes one per microsecond) and it will request the content from the server, rather then serving it from its cache.

Respondent: user2182349

Solution #4:

If you read the docs they say:

cache (default: true, false for dataType 'script' and 'jsonp')
Type: Boolean

If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending “_={timestamp}” to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

Respondent: S. Imp

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.