Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Browser from Caching

I am doing facebook app development. Something really annoy me is that randomly, when I change my CSS style sheet/ adding in a javascript function. The browser does not reflect the change at all. This is really annoying because I can never see the changes I just made.

For example. I changed my CSS style sheet so img1 is moved from 100px to 50px. But in firfox/chrome, the img never moved a bit.

I added a javascript function a() to one of my script. But the browser's console keeps telling me a() is not defined. I have checked through the codes 10 times and there is no error.

Can someone tell me what is the possible problem here and how to solve it?

I am using my mac as the hosting server btw

Thanks

like image 297
Codier Avatar asked Jan 28 '26 12:01

Codier


1 Answers

You can add a timestamp or other unique string to the filename of the files you don't want to be cached, either in the actual filename or as a GET parameter:

<link rel="stylesheet" type="text/css" 
      href="http://cdn.sstatic.net/stackoverflow/all.css?v=4fd8a9d8937d">

Depending on the server-side language you're using to server your pages, you could do something like:

PHP (using filemtime - which returns the modification time of a file):

<link rel="stylesheet" type="text/css" 
      href="http://cdn.sstatic.net/stackoverflow/your_css_file.css?v=<?php echo filemtime('/your_css_file.css'); ?>">

Ruby (using File.mtime which returns the modification time of a file):

<link rel="stylesheet" type="text/css" 
      href="http://cdn.sstatic.net/stackoverflow/your_css_file.css?v=<% print File.new("testfile").mtime.to_time.to_i('/your_css_file.css'); %>">

If you use the file's modification time, your users are only forced to download the file again if it has been modified.

like image 69
Michael Robinson Avatar answered Jan 30 '26 01:01

Michael Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!