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.