Skip to content

Instantly share code, notes, and snippets.

@kickscondor
Last active August 24, 2018 16:53
Show Gist options
  • Save kickscondor/55020db25cf973c17e2a1098c89fac95 to your computer and use it in GitHub Desktop.
Save kickscondor/55020db25cf973c17e2a1098c89fac95 to your computer and use it in GitHub Desktop.
# Simple plugin for hashing assets in Jekyll and adding a fragment of the
# hash to the file's path as a query string.
#
# Example:
#
# <link rel="stylesheet" href="/{% bust css/main.css %}">
#
# Outputs:
#
# <link rel="stylesheet" href="/css/main.css?5bbb9e1">
#
# You also have to turn this plugin on in your config.yml using the
# 'cache-bust' option:
#
# cache-bust: true
#
# I use multiple _config.yml files to manage my different output formats
# and some cache bust and others don't.
#
# Lastly, this plugin does cache the MD5 hashes so that the file doesn't
# get rehashed over and over again when you build.
#
require 'digest/md5'
module Jekyll
class CacheBustTag < Liquid::Tag
MD5_CACHE = {}
def initialize(tag_name, file_name, tokens)
super
@file_name = file_name.strip
end
def md5
h = MD5_CACHE[@file_name]
unless h
h = MD5_CACHE[@file_name] = Digest::MD5.file(@file_name).hexdigest[0, 7]
end
h
end
# Gets Md5 contents of target file (assumed to be using the full path)
# and appends a hash end of to asset file reference. Ensures deployed
# asset files are "cachebust-ed" every time the file changes
def render(context)
if context.registers[:site].config['cache-bust']
"#{@file_name}?#{md5}"
else
@file_name
end
end
end
end
Liquid::Template.register_tag('bust', Jekyll::CacheBustTag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment