简体   繁体   中英

Can I cache contents loaded by jQuery.getScript()

As per jQuery documentation ( https://api.jquery.com/jquery.getscript/ ) use more flexible $.ajax() method, but it doesn't work for me described in here ( jQuery cannot load plugin file using ajax before calling the plugin function, thus, gives kind of weird result )

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. You can override this feature by setting the cache property globally using $.ajaxSetup() :

$.ajaxSetup({
  cache: true
});

But I need to cache few of the contents not all.

Alternatively, you could define a new method that uses the more flexible $.ajax() method.

It didn't work for me as it doesn't guarantee loading files in a sequence.

Now what is the best solution for this situation?

$.getScript({
    url: "foo.js",
    cache: true
})

Supported on jQuery 1.12.0 or later

use $.ajax with dataType: 'script' and cache: true .

$.ajax({
    cache: true,
    url: 'foo.js',
    dataType: 'script', // optional, can omit if your server returns proper contentType for js files.
    success: function () {
        console.log('Hello World!');
    }
});

This assumes your server is responding with the headers required for the browser to cache the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM