Optimizing Ghost theme CSS files

I recently updated this site to Ghost v1.5.2 and took the chance to update the theme. The site now uses the Blacklist theme.

Out of the box it's a pretty speedy theme with Google Pagespeed ranking it a 91 on Desktop and 74 on Mobile. The main issue for both tests is the optimization of the CSS files. That is, the themes loads 4-6 CSS/font files instead of bundling them into a single optimized CSS file.

Since bundling files is dead simple these days I decided to spend a few minutes to make this optimization. Here's how.

Let's Bundle

First, navigate to your theme directory, located at:

/ghost/content/themes/[theme-name]

Then we need a tool to do the heavy lifting for us. I did a few searches for a npm package and quickly settled on the promising clean-css-cli package.

Install the package with:

npm install -g clean-css-cli

Now we'll bundle all the CSS files together. If I view my sites's source I see 4 CSS files being loaded. If you look the default.hbs template file you should see the code loading the CSS files. Something like:

<link rel="stylesheet" type="text/css" href="{{asset "css/min/screen.min.css"}}" />
<link rel="stylesheet" type="text/css" href="{{asset "css/min/animate.min.css"}}" />
<link rel="stylesheet" type="text/css" href="{{asset "css/min/pace.min.css"}}" />
<link rel="stylesheet" type="text/css" href="{{asset "fonts/icons/icons.css"}}" />

Our goal here is to bundle these 4 files into a single, minimized CSS file, but first we need to prepare the HTML for the new file. Remove all the <link ... lines with a single line of

<link rel="stylesheet" type="text/css" href="{{asset "css/app.min.css"}}" />

Then restart Ghost with

ghost restart

Now run the cleancss command to bundle the 4 CSS files. In my case, for the 4 files above I ran:

cleancss -o ./assets/css/app.min.css
  ./assets/css/min/screen.min.css
  ./assets/css/min/animate.min.css
  ./assets/css/min/pace.min.css
  ./assets/fonts/icons/icons.css

The first argument after -o is where the output will be saved, which is the new <link ... we used above.

Once cleancss finishes you should have a new minimized CSS file.

Reload your site to make sure the styles or the same as before, and if so, you're good to go.

Final Notes

Keep in mind that updating your theme will overwrite these changes. You just need to repeat the quick process to bundle the file again.

Comments