javascript - 从回调中创建 XMLHttpRequest 如何影响缓存?

标签 javascript http caching xmlhttprequest cache-control

在浏览器中检索以下 HTML 时,浏览器会为在主范围内发出的 XHTTP 请求设置缓存控制 header ,但不会为超时回调发出的请求设置缓存控制 header 。这会导致第二个资源总是从缓存中加载,除非缓存不存在。为什么将请求放在回调中会像这样影响缓存 header ?

<!DOCTYPE HTML>
<html>
  <body>
    <script type="text/javascript">

      var get = function (url) {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", url, true);
        xhttp.send();
      }

      get("resource1.html");    // Cache-control set

      setTimeout(function () {
        get("resource2.html");  // Cache-control not set
      }, 10);

      get("resource3.html");    // Cache-control set

    </script>
  </body>
</html>

(我已经在我手头的所有机器和浏览器上测试了这个,结果非常一致。一个异常(exception)是如果超时设置为 Firefox 似乎确实为回调资源设置了缓存控制 header 0,其他浏览器仍然没有)。

最佳答案

暂时无法重现,但让我们尝试回家......

我测试过:

app.js

router.get(/resource./, function(req, res) {
  res.setHeader('Cache-Control', 'public, max-age=90');
  res.send('<hr/>');
});
router.get('/', function(req, res) {
  res.render('index');
});

index.html

<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">

    var get = function (url) {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", url, true);
        xhttp.send();
    }

    get("resource1.html");    // Cache-control set

    setTimeout(function () {
        get("resource2.html");  // Cache-control not set
    }, 10);

    get("resource3.html");    // Cache-control set

</script>
</body>
</html>

他们都得到了 200 的...

enter image description here

和缓存控制

HTTP/1.1 200 OK
X-Powered-By: Express
Cache-Control: public, max-age=90
Content-Type: text/html; charset=utf-8
Content-Length: 5
ETag: W/"5-mkFFtL4+3G6hWYdNAMJUPw"
Date: Thu, 03 Mar 2016 16:09:48 GMT
Connection: keep-alive

此外,日志:

第一次

Listening on port 3000
GET / 200 12.544 ms - 499
/resource1.html undefined
GET /resource1.html 200 1.389 ms - 5
/resource3.html undefined
GET /resource3.html 200 0.353 ms - 5
/resource2.html undefined
GET /resource2.html 200 0.233 ms - 5

第二次

GET / 200 1.627 ms - 499
/resource1.html no-cache
GET /resource1.html 200 0.427 ms - 5
/resource3.html no-cache
GET /resource3.html 200 0.160 ms - 5
/resource2.html no-cache
GET /resource2.html 200 0.408 ms - 5

关于javascript - 从回调中创建 XMLHttpRequest 如何影响缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35660213/

相关文章:

javascript - 混合类型 react 的映射函数中的 typescript 类型问题

javascript - 使用 JavaScript 在 HTML 中查找输入

python - 如何实现SSDP/UPnP?尝试使用索尼的相机 API

java - Guava LoadingCache - 如何处理后备存储中不存在的键

javascript - 通过PeerJS接收数据

javascript - Jquery点击函数无法识别

javascript - 在 Koa.js 中仅重定向未经身份验证的用户以查找丢失的资源?

http - 我如何通过 Guile Scheme 检查 URL 是否存在?

java - 使用 Aerospike bin 名称的最佳做法是什么?

python - 语句/查询缓存与 Python 数据库库和绑定(bind)参数?