My site uses several common CDN hosted resources, like bootstrap.css
, jquery.js
and fontawesome.css
. Is it possible to get information, probably with JavaScript, do my site visitors have warm caches for these resources in their web browsers?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
While not an answer, some interesting insight I found when working on this problem with Chrome:
Fetching the resource from CDN is a deferred call, while fetching an item from the cache seems in fact to be a blocking call, despite being quite fast.
Firefox didn't seem to this exhibit behavior consistently (and I didn't even bother with IE).
To test this observation further, I built the following small fiddle, which works reliably for me on Chrome. Please leave a comment on your own test results if you have the time.
var testSource = function(href) {
var timeLimit = 5;
var l = document.createElement("link");
l.rel = "stylesheet";
l.type = "text/css";
l.href = href;
var s1 = document.createElement("script");
s1.innerHTML = "window.d = new Date();";
var s2 = document.createElement("script");
s2.innerHTML = "window.d2 = new Date();";
document.head.appendChild(s1);
document.head.appendChild(l);
document.head.appendChild(s2);
window.setTimeout(function() {
var p = document.createElement("p");
if (typeof(d2) === "undefined" || d2 - d > timeLimit) {
p.innerHTML = "guess cache";
} else {
p.innerHTML = "guess load";
}
p.innerHTML += " (" + href + ")";
document.body.appendChild(p);
},
timeLimit * 10);
}
btn.onclick = function() {
testSource(inp.value);
}
<input type="text" id="inp" value="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
<input type="button" id="btn" value="test url" />