How to Add Custom Script to Single Post in Jekyll
Here’s how I’ve implemented the ability to add JavaScript and CSS files to specific posts in Jekyll.
What I want:
- Embed a simple JavaScript and CSS demos directly in a post.
- Be able to add multiple JavaScript and CSS files.
- All scripts should be added to the
<HEAD>
tag. - No need for dependencies between scripts during loading.
Implementation Details
Include file custom-scripts.html
contains all the logic for the rendering:
This include expects two page variables custom-javascript-list
and custom-css-list
and renders tags for each value in these lists.
The call to this include is added to the head.html
which renders the content of the <HEAD>
tag.
Usage Example
To test new functionality I added animate.css for animation effects and jQuery to this page. Try clicking on the label below (hint: it should bounce):
Click Me!
And here is how it’s implemented. For the current post, the front matter header contains links to files on CDN:
During processing this will be rendered into the following lines:
Now I can reference jQuery and animate.css functionality. Jekyll allows to use HTML and JavaScript code directly in markdown files.
Below is the code for the “Click Me!” label added directly to this post. The jQuery
code gets element by its id and sets the animate.css class to bounce (inline CSS styles are omitted for brevity). After a second the CSS classes got removed, so they can be applied again:
Alternative Solutions
If you’ve got requirements that make this approach not feasible, here are two more options that you can use:
- Create a new page. Create a new page, not post, and define all the HTML in it, including custom JavaScript and CSS references. This makes editing text harder because you’ll need to control the layout yourself, but gives you flexibility.
- Use external sites such as JSFiddle or CodePen to run your JavaScript and CSS code.