Load page-specific CSS and JavaScript in Jekyll
Some pages need an extra stylesheet or script, but that does not mean every page should download it. Jekyll front matter can tell the layout which assets to include.
Add the asset names to the page’s front matter:
---
css:
- custom.min
js:
- jquery.min
---
Using lists here matters because the template loops over the values. It also lets a page load more than one file later.
In the layout’s <head>, add the stylesheet loop:
{% if page.css %}
{% for stylesheet in page.css %}
<link rel="stylesheet" href="{{ site.baseurl }}/assets/css/{{ stylesheet }}.css">
{% endfor %}
{% endif %}
Place the script loop where your site normally loads JavaScript, often near the end of <body>:
{% if page.js %}
{% for js_file in page.js %}
<script src="{{ site.baseurl }}/assets/js/{{ js_file }}.js"></script>
{% endfor %}
{% endif %}
Pages without css or js in their front matter produce no extra tags. That keeps one-off code off the rest of the site, which is usually the reason to use this pattern in the first place.
Enjoyed reading this?
If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.
Related articles
- The HTTP Status Codes I Actually Check
A practical guide to common HTTP response codes, redirects, client and server errors, and the headers that explain them.
- What Makes a Website a Progressive Web App?
A practical look at service workers, web app manifests, installation, and the cases where a Progressive Web App is worth building.
- What a Static Site Generator Actually Does
A static site generator combines content and templates before deployment, producing HTML files that a web server can deliver directly.