Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c# - How to check if browser caching disabled

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATE

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.

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();

After that you can simply check for cacheEnabled === true or cacheEnabled === false after some period of time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...