Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an external script for a Jekyll page?

I'm building a Jekyll site on GitHub Pages. I have a particular page that needs a small bit of JavaScript. The header and body tags of this page are controlled by the theme I am using. I would like to maintain this JavaScript in an external script file rather than using raw script in the middle of my page.

Given modern web technology, is there any major gotcha to simply using an async script tag to load the file? This tag would appear inside the body content once the page is generated, but as far as I can tell the recommendation to not load external scripts in the body originally came from loading speed concerns and is somewhat no longer valid with async. The script is small and controls non-critical functionality.

Basically:

<body>
  ...page content...
  <script src="/assets/js/myscript.js" type="text/javascript" async=""></script>
  ...page content...
</body>

I could override the theme layout to access the header directly and do this more traditionally, but I'd like to avoid that if possible. Is there another recommendation for using small one-off scripts with Jekyll?

like image 891
Shaun Hamman Avatar asked Mar 07 '23 00:03

Shaun Hamman


1 Answers

Ultimately, Jekyll markdown is converted to standard HTML, so this question is reduced to "Is it safe, performance-wise, to load small, non-critical async external scripts in the HTML body?".

See https://stackoverflow.com/a/39711009 for a diagram showing how async works. I will copy it below for clarity. It shows us that the resource is requested in parallel with HTML parsing, making the performance hit roughly equivalent to running inline JS. Therefore, if the script is small (assuming by small, you mean that it is not resource intensive, as opposed to small in terms of code length), the performance hit will be negligible, regardless of where you put it.

If the script is non-critical, it would still be best be put it at the end of the body if possible, so that the critical HTML and other resources are loaded first, because the HTML parsing is still paused when executing the script.

enter image description here

The Google Chrome Lighthouse tools can be used to give an indication of performance of a web page, and shows which parts of your web page are causing the biggest hit to performance, which in my experience tends to be images. You can use these tools by opening the Chrome Dev Tools, and going to the Audit tab.

like image 95
A Jar of Clay Avatar answered Mar 09 '23 07:03

A Jar of Clay