views:

1606

answers:

3

How can I check for a javascript file in user's cache. If he refreshed the page or visits the site after sometime. I need not download that js file again. Does the js files get cleaned up after a site is closed.

+4  A: 

Whether a javascript file is cached depends on how your web server is setup, how the users browser is setup and also how any HTTP proxy servers between your server and the user are setup. The only bit you can control is how your server is setup.

If you want the best chance of your javascript being cached then you server needs to be sending the right HTTP headers with the javascript file. Exactly how you do that depends on what web server you are using.

Here are a couple of links that might help:

Apache - http://httpd.apache.org/docs/2.0/mod/mod_expires.html

IIS - http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0fc16fe7-be45-4033-a5aa-d7fda3c993ff.mspx?mfr=true

andynormancx
+1  A: 

The browser will automatically look after what it has in it's own cache. There are various mechanisms you can use for controlling it however.

Look into the various HTTP caching headers, such as:

  • Last-Modified
  • Expires
  • ETag

The Expires header is the most critical of these when it comes to client-side caching. If you set a far future Expires header (eg, 10 years) the browser will not (in theory) not look to the server again for that file. Of course then you need a method of changing the file name when the contents of the the file change. Most people manage this by adding a build number to the file path.

Andy Hume
A: 

The browser will take care of caching for you.

When the cache is emptied depends partly on the browser settings and partly on the headers you send. If you set an Expires header, then the browser shouldn't re-request the file until it has expired. Reading about HTTP Headers might help you.

Greg