How can I make the browser see CSS and Javascript changes

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

CSS and Javascript files don t change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion.


Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. http://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number http://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number

http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html

http://svnbook.red-bean.com http://svnbook.red-bean.com

Firefox also allows pressing CTRL+R to reload everything on a particular page.

To clarify I am looking for solutions that don t require the user to do anything on their part.

Answers

I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP:

function urlmtime($url) {
   $parsed_url = parse_url($url);
   $path = $parsed_url[ path ];

   if ($path[0] == "/") {
       $filename = $_SERVER[ DOCUMENT_ROOT ] . "/" . $path;
   } else {
       $filename = $path;
   }

   if (!file_exists($filename)) {
       // If not a file then use the current time
       $lastModified = date( YmdHis );
   } else {
       $lastModified = date( YmdHis , filemtime($filename));
   }

   if (strpos($url,  ? ) === false) {
       $url .=  ?ts=  . $lastModified;
   } else {
       $url .=  &ts=  . $lastModified;
   }

   return $url;
}

function include_css($css_url, $media= all ) {
   // According to Yahoo, using link allows for progressive 
   // rendering in IE where as @import url($css_url) does not
   echo  <link rel="stylesheet" type="text/css" media="  .
  . urlmtime($css_url) .  
  . urlmtime($css_url) .  
}

function include_javascript($javascript_url) {
   echo  <script type="text/javascript" src="  . urlmtime($javascript_url) .
         "></script> ."
";
}

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/3224/how-can-i-make-the-browser-see-css-and-javascript-changes

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils