I recently redesigned this site, and it’s now built statically with the excellent Jekyll.
One of my goals was to reduce the number and size of assets in each page, and particularly to trim down the CSS and eliminate as much JavaScript as possible. This very brief article is about how I did that while preserving functionality where needed.
Over the years, the site’s CSS has become bloated with what are essentially post-specific styles, only used in one or two articles and then never again. Similarly, there were JavaScript libraries that were only rarely needed, but were being downloaded every time.
What I’ve done is make those styles and libraries page-specific, using a very simple setup with Jekyll’s support for Liquid templates and YAML front matter.
In a nutshell, I use a post’s front matter to specify CSS and/or JavaScript files that apply only to that post, and they’re then loaded only on that page.
Here’s the relevant YAML, in a post that uses my Author Marks feature:
---
custom_css: authormarks
custom_js:
- jquery.min
- authormarks
---
And here’s the corresponding Liquid logic, at the end of the template for the HEAD
section of each page:
{% if page.custom_css %}
{% for stylesheet in page.custom_css %}
<link rel="stylesheet" href="/css/{{ stylesheet }}.css" media="screen" type="text/css">
{% endfor %}
{% endif %}
{% if page.custom_js %}
{% for js_file in page.custom_js %}
<script src='/javascripts/{{ js_file }}.js' type="text/javascript"></script>
{% endfor %}
{% endif %}
Given the above YAML and Liquid template, a CSS file called authormarks.css
and two JavaScript files called jquery.min.js
and authormarks.js
will be included in the relevant article’s page.
It’s a trivial example, but I thought I’d share it for fellow Jekyll users who want to make sure their pages are as light as possible.