Trouble Linking External JavaScript with Jekyll

不羁的心 提交于 2019-12-22 05:43:12

问题


I have a site hosted by GitHub that uses Jekyll, and I've been (successfully) using an internally defined script in each layout that will generate a random tagline from an array of them.

I'm trying to move this script to an external tagline.js, but so far I've been unsuccessful.

Here's the basic tagline generating script, in case there's something in the code causing this (which I doubt, honestly, due to its simplicity; but it's always a possibility):

var tags = [ 'tag1', 'tag2', 'tag3' ];

function getTag() {
    return tags[Math.floor(Math.random() * tags.length)];
}

$(document).ready(function() {
    $("#tagline").text(getTag());
});

Like I said, it works fine when it's internal, but it doesn't when I try linking to external. I'm pretty sure it's just a case of where I'm pointing the <script> to: the HTML file containing the <script> is in _layouts/default.html, but the script is in scripts/tagline.js.

EDIT: Sorry, I was using "<link>" when I actually meant "<script>". So that eliminates the solution "you're using the wrong tag"! :P

EDIT2: The full <script> (again, located in an HTML file in _layouts/default.html) is this: <script type="text/javascript" href="../scripts/tagline.js"></script>


回答1:


The attribute you want to use for a script call is src instead of href. For example:

<script type="text/javascript" src="../scripts/tagline.js"></script>

I would also highly recommend using paths from the site root (aka docroot) instead of relative to the file. That way you can use the same call in multiple places and it will always hit the correct location. To use a docroot relative URL, you start the path with a /.

Assuming your script is located at http://example.com/scripts/tagline.js, the call you would make is:

<script type="text/javascript" src="/scripts/tagline.js"></script>

Without using the docroot, you will constantly have to adjust the path depending on where the HTML file calling the script is located in the tree. If all the files are in the same place, that's not a big deal, but it's a good habit to get into to avoid issues down the road.



来源:https://stackoverflow.com/questions/12118780/trouble-linking-external-javascript-with-jekyll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!