使用XMLHttpRequest加载JS文件,浏览器是否会缓存该文件?
我正在使用XMLHttpRequest()加载部分JS文件,请问通过以下代码加载时,浏览器是否会对该文件进行缓存?代码如下:
var xhr = new XMLHttpRequest(); xhr.open("get", "example.js", true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) { var script = document.createElement("script"); script.type = "text/javascript"; script.text = xhr.responseText; document.body.appendChild(script); } } }; xhr.send(null);
Short answer: Yes, browsers will cache this request by default—but it all comes down to how the server configures cache-related HTTP headers for example.js, plus the browser's native caching rules.
Let me break this down clearly:
Default browser behavior: When you send a GET request via XMLHttpRequest (just like a regular
<script>tag loading a JS file), browsers will check their local cache first. If the file is already cached and still valid (per the cache rules), they’ll pull the cached copy instead of making a fresh request to the server. That’s exactly why you’ve included the304 Not Modifiedcheck in your code—this status code means the browser is using a valid cached version of the file.Server headers are the real control: Whether the cache sticks, how long it lasts, or if it’s used at all depends entirely on headers the server sends with
example.js. For example:- A
Cache-Control: max-age=3600header tells the browser to cache the file for 1 hour. Cache-Control: no-cachemakes the browser ask the server every time if the file has changed (but it’ll still use the cached copy if the server returns 304).Cache-Control: no-storeforces the browser to never cache the file at all.
- A
Your code handles cached responses correctly: The fact that you’re checking for
xhr.status == 304is spot-on—this ensures that even when the browser uses a cached version, your code still injects the JS content into the page properly.
If you ever need to bypass the cache intentionally, you can add a unique query parameter to the URL (like example.js?timestamp=1698765432)—this tricks the browser into treating it as a brand-new resource, skipping the cache entirely.
内容的提问来源于stack exchange,提问作者harryzcy

