With Hugo pipelines1 you can now bundle all your assets together, minify them, then fingerprint them for cache-busting. In this post I’ll discuss how I do it for my blog.
For any CSS or JS that you want to apply pipelines to, they should go in an
assets/ directory at the root of your blog.
Here’s my directory structure:
I also have a
links.html partial, which I’ll show further on in this post.
First we need to get all the assets we’ll be bundling. Obviously, you can only bundle CSS with other CSS and JS with other JS.
$variables contain the content of the file.
Next, we put them through a pipeline:
What this is doing is taking those resources you loaded above, concatenating them into one file, minifying them, then adding a cache-busting fingerprint, so your users don’t get stuck loading old versions of your JS and CSS assets.
Now I get these files output to my
public directory, i.e. the static site
Now we have all our JS and our CSS bundled, minified and fingerprinted. The next thing we can do to speed up our site is using preloading. From MDN2:
preloadvalue of the
relattribute lets you declare fetch requests in the HTML’s
<head>, specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in. This ensures they are available earlier and are less likely to block the page’s render, improving performance.
links.html partial I do preloading like this:
On line one we are telling the browser to begin downloading the bundled CSS. And
since we’ve still got the
$styleBundle variable in scope, we don’t need to
worry about the fingerprint.
onload event simply changes the
stylesheet. Since the resource has already been downloaded,
we change the
rel attribute to tell it to start using it instead of
downloading it again.
styles regularly inside a
Notice also that we are using
$styleBundle.RelPermalink, as without this the
local Hugo server won’t work, and you won’t see any of your styles.
Here’s my full
links.html partial, which is loaded in my
I’ve seen the minified bundles be as much as 40% smaller than loading each asset individually and minifying them, so I definitely recommend it if you’re trying to eke out as much performance from your blog as possible.
|Pre-bundling and minifying
|Post-bundling and minifying
It ends up being fewer network requests, and your page will be interactive faster because it loads the assets all at once rather than one-by-one.
I think for my next post I’ll look into reducing that