gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:39:14 25 4
gpt4 key购买 nike

在浏览器中检索以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com