You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用XMLHttpRequest加载JS文件,浏览器是否会缓存该文件?

Will browsers cache a JS file loaded via XMLHttpRequest like this?

我正在使用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);
Answer

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 the 304 Not Modified check 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=3600 header tells the browser to cache the file for 1 hour.
    • Cache-Control: no-cache makes 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-store forces the browser to never cache the file at all.
  • Your code handles cached responses correctly: The fact that you’re checking for xhr.status == 304 is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:27:44