Prevent Your CSS and JavaScript Files From Being Cached

Some websites use highly volatile, oft-changing CSS and JavaScript files. In the case of these files, it’s important that the developer prevent browsers from caching them. How do we do that? By using a phantom querystring, of course. We’ll use PHP to tack the current time onto the file reference.

The PHP

<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" >
<-- RENDERS -->
<link href="/stylesheet.css?1234567890" rel="stylesheet" type="text/css">

<script type="text/javascript" src="/site-script.js?<?php echo time(); ?>"></script>
<-- RENDERS -->
<script type="text/javascript" src="/site-script.js?1234567890"></script>

It’s a very simple technique and doesn’t affect your CSS or JavaScript code in any way.

Resource :

http://davidwalsh.name/prevent-cache

Leave a comment