问题描述
是否有可能(没有应用程序层的请求缓存)在可缓存时阻止多次发送针对同一资源的HTTP请求?如果是的话,怎么办?
例如代替
at time 0: GET /data (request#1)
at time 1: GET /data (request#2)
at time 2: received response#1 for request#1 // headers indicate that the response can be cached
at time 3: received response#2 for request#2 // headers indicate that the response can be cached
at time 0: GET /data (request#1)
at time 1: GET /data (will wait for the response of request#1)
at time 2: received response#1 for request#1 // headers indicate that the response can be cached
at time 3: returns response#1 for request#2
这将要求它有可能在读取响应头之前向浏览器指示该响应是可缓存的。我问是否有这样的机制。例如。前面带有某种OPTIONS或HEAD请求。
解决方法
我的问题是,是否有一种机制可以向浏览器发出URI响应可到达的信号
是的,这就是Cache-control
标头的作用。
及对该URI的任何后续请求都可以返回任何正在进行的请求的响应...。理想情况下,这将是HTTP规范的一部分
没有HTTP不能为您做到这一点,您需要自己实现缓存。这就是浏览器的作用。
我确实想检查一下是否有现成的东西
JavaScript库通常不支持缓存,因为AJAX请求通常用于数据,任何数据缓存通常在服务器上进行。我不知道任何图书馆,当然还有asking for Js libraries is out of scope on SO。
,根据浏览器的不同,第二个请求(如果可缓存)可能会暂停并得到处理,例如在Chromium中用于非范围请求:
高速缓存实现单个写入器-多个读取器锁,因此在任何给定时间只有一个网络请求针对同一资源。 https://www.chromium.org/developers/design-documents/network-stack/http-cache
下面是一个示例,其中三个并发请求仅导致一个服务器调用:
fetch('/data.json').then(async r => console.log(await r.json()));
fetch('/data.json').then(async r => console.log(await r.json()));;
setTimeout(() => fetch('/data.json').then(async r => console.log(await r.json())),2000);
后续请求已转移0B并具有相同的随机数,表明仅进行了一次服务器调用。
想到interesting question是在对资源进行H2推送之前(但尚未完成)提出资源请求时会发生的情况。
要在此处复制测试代码: https://gist.github.com/nickrussler/cd74ac1c07884938b205556030414d34