Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 670
gaffleck Avatar asked Nov 05 '22 06:11

gaffleck


1 Answers

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.

like image 138
Pavel Podlipensky Avatar answered Nov 07 '22 20:11

Pavel Podlipensky