Smart Tech for a better Web

How to inline JavaScript with Jekyll


Inlining CSS can help your site to look better with Google PageSpeed. Small portions of JavaScript are better not loaded using an external file, as the HTTP overhead is bigger than the size.

How to change css classes

But define what “big” is. To satisfy Google, I tend to inline even “bigger” junks of JavaScript.

For that, I use a build system like Gulp.JS to help me with that task. I usually write my code in a folder called _js. From there it should be uglified, concatenated and whatever else. The result needs to go to the _includes folder. Once it arrived there, I can include it from my Jekyll template.

Here is my Gulp task:

gulp.task('js', function () {
       .pipe(rename({ extname: '.min.js' }))

First I take my sources from the JavaScript folder (usually more than one), concatenate it and write it to the generated folder. The unminified version is helpful when you want a readable file for debugging.

Then I rename it and uglify it.

The dependencies I use in “package.json” is:

    "dependencies" : {
        "gulp" : "^3.9.0",
        "gulp-uglify" : "1.2.0",
        "gulp-concat" : "2.5.2",
        "gulp-rename" : "^1.2.2"
    "private": true

Now you can easily include the generated file with:

<script type="text/javascript">{% include generated/app-full.min.js %}</script>

But be careful. Frameworks like MinifiedJS come with template features. As Jekyll, they use {{ … }} for their template language. Jekyll consider your include as Liquid layout, which means it will try to parse your code - and replace things!

This all caused me some grief.

But there is a solution: the raw tag. Everything inside this tag will not be parsed as Liquid.

In package.json, add a new dependency like gulp-insert:

"gulp-insert" : "^0.5.0"

This little plugin lets you write some additional content to your stream. In my case, I added the raw tag:

gulp.task('js', function () {
       .pipe(rename({ extname: '.min.js' }))

       .pipe(insert.wrap('{ % raw %}', '{ % endraw %}'))


NOTE: I had to add a blank in the raw-tags to avoid problems with rendering this blog post…

I would recommend you to add the raw tag to any JavaScript files you include. Prevents a headache.

Image credits

Tags: #JavaScript #MinifiedJS #Jekyll