Thursday, October 10, 2013

Wordpress: Force browsers to load the latest CSS and JS

During development of a website or modifications later, the caching of .css and .js files can be a real problem, especially when dealing with less tech-savvy clients. Adding a parameter solves this as the browser is forced to re-download the file. The best soultion seems to be adding the file modification date as the parameter, so whenever you modify the file, the parameter will change automatically.

To implement this in Wordpress, put these two functions in your theme's functions.php:

 // Always fresh css includer  
 function insertCss($file) {  
      $cssFile = get_bloginfo('template_directory') . '/' . $file;  
      $cssFilePath = get_template_directory() . '/' . $file;  
      $csstime = @filemtime($cssFilePath);  
      return $cssFile . '?v=' . $csstime;  
 };  
 // Always fresh js includer  
 function insertJs($file) {  
      $jsFile = get_bloginfo('template_directory') . '/' . $file;  
      $jsFilePath = get_template_directory() . '/' . $file;  
      $jstime = @filemtime($jsFilePath);  
      return $jsFile . '?v=' . $jstime;  
 };  

In the header use them like this:

 <link rel="stylesheet" href="<?php echo insertCss('style.css'); ?>" type="text/css" />  
 <script type="text/javascript" src="<?php echo insertJs('js/functions.js'); ?>"></script>  

No more angry calls demanding a change you already made...


Update:

I updated my empty wordpress theme to include these and the shorttext functionality I wrote about here. You can download it here: https://docs.google.com/file/d/0ByJLxNUdJ5J-OE54amp1YWJ5Y28/edit?usp=drive_web
(Press Ctrl+s)