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

Ian*_*non 6 javascript caching http xmlhttprequest cache-control

在浏览器中检索以下HTML时,浏览器会为主范围内的XHTTP请求设置Cache-control标头,但不会针对超时回调发出的请求设置.这会导致始终从缓存加载第二个资源,除非缓存不存在.为什么将请求放在回调中会影响这样的缓存头?

<!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>
Run Code Online (Sandbox Code Playgroud)

(我已经在我手边的所有机器和浏览器上对此进行了测试,结果非常一致.一个例外是,如果超时设置为0,Firefox似乎确实为回调资源设置了一个Cache-control标头,其他浏览器仍然没有).

mal*_*lix -1

目前无法重现,但让我们尝试回家......

我测试过:

应用程序.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');
});
Run Code Online (Sandbox Code Playgroud)

索引.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>
Run Code Online (Sandbox Code Playgroud)

他们都拿了200多...

在此输入图像描述

和缓存控制

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
Run Code Online (Sandbox Code Playgroud)

另外,日志:

第一次

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
Run Code Online (Sandbox Code Playgroud)

第二次

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
Run Code Online (Sandbox Code Playgroud)