I have a site hosted by GitHub Pages 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
:
<script type="text/javascript" href="../scripts/tagline.js"></script>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With