Keeping your CDN-hosted CSS and JS from caching and causing you to rip your hair out

CDNs are great for distributing bandwidth and speeding up your site, but if you’re using a static pull, you’re going to have an issue if you make a tiny tweak to your CSS file, unless you invalidate the file in your CDN panel. Of course, that’s not always practical, and it takes a few minutes to take. However, version numbers make everything work smoothly!

This is my simple fix to dealing with CDN and versioning. I’m using this in WordPress, but it can be easily adapted to pretty much anything.

function get_version_from_datestamp($str_file){
 $str_version = date ('y.n.j.G.i', filemtime($str_file)); //YY.M.D.H.MM
 return $str_version;
}

This function takes the full path to the file and returns a version number based off of the date (my full function assumes just a relative path and then appends the full file path to it). When using wp_register_script or wp_register_style, simply call this in place of a static version number. When you update the file on the server, it automagically updates the version number! No fuss, no muss, no invalidating, no worrying about the version number itself.

  • Hilarity ensues:

    I haven’t had the chance to add this to this site yet, but I changed the style sheet when I noticed that the wrapping post title needed some better line spacing. W3TC’s minifier didn’t notice the change, so I spent about 30 seconds trying to figure out why it wasn’t showing up.

    D’oh!