如何检查是否浏览器缓存禁用 [英] How to check if browser caching disabled

查看:593
本文介绍了如何检查是否浏览器缓存禁用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有Javascript或C#的方式来告诉浏览器是否有人在使用已禁用的静态内容缓存?

Is there a way in either Javascript or C# to tell if the browser that someone is using has disabled caching of static content?

我需要能够测试浏览器是否缓存了优化。

I need to be able to test whether or not the browser is optimized for caching.

推荐答案

更新

我做的问题多一点调查,你可以找到更详细的答案在我最近的帖子
注意,以下描述的溶液(最初)不是跨浏览器溶液

I did a bit more investigation of the problem and you can find more detailed answer in my recent post Note, the solution described below (initially) is not cross browser solution.

不知道是否有帮助,但你可以试试下面的技巧:
1.添加一些资源给你页面,让我们说这将是JavaScript文件 cachedetect.js
2.服务器应生成 cachedetect.js 每次有人提出要求。它应该包含在响应缓存相关的头,也就是说,如果浏览器的缓存被启用,应缓存很长一段时间的资源。每个 cachedetect.js 应该是这样的:

Not sure if it helps, but you can try the following trick: 1. Add some resource to you page, let's say it will be javascript file cachedetect.js. 2. The server should generate cachedetect.js each time someone request it. And it should contain cache-related headers in response, i.e. if browser's cache is enabled the resource should be cached for long time. Each cachedetect.js should look like this:

var version = [incrementally generated number here];
var cacheEnabled; //will contain the result of our check
var cloneCallback;//function which will compare versions from two javascript files

function isCacheEnabled(){
   if(!window.cloneCallback){
       var currentVersion = version;//cache current version of the file
       // request the same cachedetect.js by adding <script> tag dynamically to <header>
       var head = document.getElementsByTagName("head")[0];
       var script = document.createElement('script');
       script.type = 'text/javascript';
       script.src = "cachedetect.js";
       // newly loaded cachedetect.js will execute the same function isCacheEnabled, so we need to prevent it from loading the script for third time by checking for cloneCallback existence       
       cloneCallback = function(){
           // once file will be loaded, version variable will contain different from currentVersion value in case when cache is disabled 
           window.cacheEnabled = currentVersion == window.version;        
       };      
       head.appendChild(script);

    }  else {
        window.cloneCallback();
    }   
}

isCacheEnabled();

之后,你可以简单地检查 cacheEnabled ===真正 cacheEnabled ===虚假一段时间后,时间。

这篇关于如何检查是否浏览器缓存禁用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆