Site versioning with Jekyll/Octopress

When you’re editing the design and scripts on a static site that has good caching implemented, seeing your changes can be tricky. The easiest way around it is to add a “cachebuster” version string to the file includes.

Here’s a simple trick for implementing versioning for CSS and JS files on a Jekyll/Octopress site. With a couple of minor additions to your config file, Rakefile and .htaccess, you won’t have to think twice about caching when testing.

In _config.yml

Add a “version” parameter anywhere in your _config.yml file. For ease of use I placed mine near the top.

version: 1

In your templates.

Anywhere in your templates, use site.version where you want to include your version number. I’m using an htaccess trick (below) to convert urls like style.58.css to style.css with cachebusting.

<link href="/stylesheets/screen.{{ site.version }}.css">

You can also use a query string:

<link href="/stylesheets/screen.css?{{ site.version }}">

In .htaccess

If you use the first method mentioned above, you can use this trick found in the HTML5 Boilerplate in your .htaccess file:

<IfModule mod_rewrite.c>
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L]

Using this method does not require you to actually rename any files. It will just take the versioned filename from your template and read it as a fresh file when you update.

rake bump

I use the following rake task and include it in my gen_deploy task to increment the version number after I make changes and every time I do a full generate and deploy:

desc "Bump version number"
task :bump do
  content ='_config.yml')
  content.sub!(/^version: (\d+)$/) {|v|
      ver = $
      notify "At version #{ver}",:quiet => true
      "version: #{ver}"
  }'_config.yml','w') do |f|
    f.write content

This reads in your _config.yml file, searches for the version: XX line and replaces it with a line containing an incremented version number. If you run rake bump now, it will increment your version number and the next build will include updated versioning for all of the site.version mentions in your template files.

If you locate the Octopress gen_deploy task, you can add the bump task to it to run automatically:

desc "Generate website and deploy"
task :gen_deploy => [:integrate, :bump, :generate, :deploy] do

It’s an easy-to-add trick that makes updating your site design and JavaScripts that much simpler.

Brett Terpstra

Brett is a writer and developer living in Minnesota, USA. You can follow him as ttscoff on Twitter, GitHub, and Mastodon. Keep up with this blog by subscribing in your favorite news reader.

This content is supported by readers like you.