2012年4月7日星期六

How to Force Browsers to Refresh CSS for Your WordPress Blog

How can you force your reader’s browser to refresh CSS files when you change CSS stylesheets in WordPress blogs? Unless you force CSS refresh, the regular visitors browser continues to load the old cached CSS files and new changes to the CSS on your site are never visible till the user decided to refresh the page, wherein the browser clears the CSS from the cache and loads a fresh current CSS file.


If you made minor changes, old cached CSS files might not make a difference. But what it you made substantial structural changes, or introduced new classes… your site would appear totally broken to regular visitors.  How many readers would think that refreshing the page will fix your site?


css stylesheet


Force CSS Files Refresh


The answer is to force browsers to load the latest CSS file.


1. The way to do this is to change to a new CSS file name in the HEAD of the html, that will force the browser to load a new stylesheet file. But if you edit your CSS too frequently, its cumbersome to keep fixing new CSS files everytime and editing the source stylesheet name everytime.


I used to keep 3 CSS files like style1.css, style2.css, style3.css and keep cut pasting the latest code edits to the new one and updating the header.php file. An easier way is to add a so called version to your CSS file everytime like ?v=25122011, this will change the file name and force a refresh, but then again you have to change the file name everytime you edit WordPress stylesheets.


2. Then I came upon this nice trick suggested by WordPress developer Mark Jaquith, which suggests you use the function filetime which adds the server time the file was changed to the CSS url. Here is the code – cut and paste and try for yourself.


<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); echo '?' . filemtime( get_stylesheet_directory() . '/style.css'); ?>" type="text/css" media="screen, projection" />


So we used this code and now our stylesheet call code in the HEAD looks like this
<link rel="stylesheet" href="http://www.quickonlinetips.com/archives/wp-content/themes/qot/style.css?1324491378" type="text/css" media="screen, projection" />


You note that the new code has made our stylesheet style.css?1324491378 – This number will change whenever we save a new version of the style.css and will force site visitors to load the fresh copy of the CSS file.


A smart trick which makes web designing easy for bloggers who like to tweak their site design every day…





Related articles you might like ...

没有评论:

发表评论