jQuery keeps putting a cache buster in my CDN scri

2020-03-26 04:42发布

问题:

I have a script that uses $.get( ... ) to pull a piece of HTML from my server, and render it inside a <div> with $.html. Sometimes I have <script> tags in the pulled HTML, and I noticed that jQuery is putting a cache buster parameter in the request for these scripts and it's causing the browser to request again for scripts that have already been loaded.

For example:

Any idea how I can disable this behavior?

The script tags don't have the _ param attached to them so it isn't my HTML that's the problem.

Also, <script> tags that aren't rendered with $.html aren't exhibiting this behavior.

回答1:

When jQuery sees a <script src="URL"> tag in the HTML, it uses $.getScript() internally to load the script. By default, this sends a cachebuster, but you can override the default AJAX options by calling $.ajaxSetup().

$(document).ready(function () {
    $.ajaxSetup({
        cache: true
    });
    var x = '<script src="https://d9zdvmiwibsh5.cloudfront.net/js/json.js">';
    $('#test').html(x);
});

DEMO