in PHP

Force Browsers To Load Latest CSS And JS

In modern browsers they will cache most external aspects of the website, they will cache all images and even stylesheets and javascript files of your website. During a website redesign where you can change the HTML and CSS files, when you go live with these changes there will be some visitors which will come back to your site and view your page with your old stylesheet. Viewing a new page with an old stylesheet will obviously not display correctly. There are a few tricks that developers can do to make sure that browsers will download an up to date version of the stylesheets and javascript, this is done by putting a querystring to the end of the URL for the stylesheet.

http://example.com/stylesheet.css?v=1

Then when you make a change to your stylesheet you just have to simply change the version of your stylesheet to 2.


http://example.com/stylesheet.css?v=2

This is fine as it forces the browser to get the latest version as they see this as a different URL. But the developer has to remember to update this value every time they make a change to the stylesheet, which you can easily be forgotten. Another technique I've seen is to use time() to add the current timestamp to the end of the stylesheet URL.


http://example.com/stylesheet.css?v=<?php echo time(); ?>

The problem with this is that the URL will be completely different on each page load even is the stylesheet hasn't changed, therefore the browser will download a new version even if it hasn't got to. What you should be doing is getting the last modified time of the stylesheet file and add this to the end of stylesheet URL by using the filemtime() function.


<link rel="stylesheet" type="text/css" href="http://example.com/stylesheet.css?v=<?php echo filemtime($pathToCSS); ?>" />

Using With WordPress

To include a stylesheet in WordPress you should be using the function wp_enqueue_style() function (unless it's the main style.css file). This function takes a number of different parameters the 4th parameter allows you to pass in a version number that will be added to the end of the stylesheet URL.


add_action( 'wp_enqueue_scripts', 'add_styles' );

function add_styles()
{
     $css_file = get_stylesheet_directory() . '/css/style.css';
     wp_enqueue_style( 'css-file', $css_file, NULL, filemtime($css_file) );
}

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email