quimnuss
quimnuss

Reputation: 1561

How to include a javascript from /js/ in jekyll

I've added the cookie consent code from here

It has

<script>
...
if(readCookie('cookie-notice-dismissed')=='true') {
    {% include ga.js %}
    {% include chatbutton.js %}
}
...
</script>

in the html. This is placed within _includes but I can't figure out how to include javascript like /js/foo.js, located in another directory. I believe this is bundled with bundler within the jekyll assets.

Up to now, I've added javascript on my layouts in the following way, but haven't used {% include %} for this yet and I don't know how to let the _includes/cookie_consent.html know ẁhere to find it.

<script src="/js/foo.js"></script>
<script>
    $(function(){
        new Foo(".js-foo");
    });
</script>

Upvotes: 3

Views: 2293

Answers (1)

RobbeVP
RobbeVP

Reputation: 397

I can see two options to solve this

  1. you create a file in _includes that contains the links to the extra JS you want. For example:
# /_includes/bar.html
<script src="/js/foo.js"><\/script>

Inside _cookie_consent.html you can then add{% include bar.html %}

  1. You add the link directly to your body.
if(readCookie('cookie-notice-dismissed')=='true') {
    const js = '<script src="/js/foo.js"></script>'
    document.body.appendChild(js)
}

Upvotes: 1

Related Questions