Published: 2017/06/13 Reading Time: 4 minutes

Load JavaScript Dynamically to Improve Performance

Load JavaScript dynamically on a page.Occasionally, you may find the need to load JavaScript dynamically on a WordPress site, much like I do with syntax highlighting. This can be accomplished by loading a smaller, "checker" script on the page. The script will first check the page markup after loading it, and then load and execute external JavaScript code only if it passes a defined set of rules.

Why Load JavaScript Dynamically?

When you decide to load JavaScript dynamically, even though it may require a little extra effort, you avoid needlessly loading libraries or plugin's when they aren't needed, and thus boosting your website's performance in the processs. Add in the bonus that the script to load other scripts is very small, and your general page-weight (and perceived load time) will dramatically improve.

Building The Script

A quick note: I'll be using ES6 syntax for this tutorial. If you are not familiar with basic ES6 syntax ( like template strings), I would suggest getting a handle on it first). First, create a new file called checker.js (or whatever you like). Once that's created, open it up in an editor and set up an event listener on the DOMContentLoaded event:

document.addEventListener('DOMContentLoaded', () => {});

Setting the event listener here allows us to check the outputted markup of the page after it's available, but before the page has finished it's loading cycle (a quick note here that, depending on when the file is registered, using this event listener can cause problems). Next, let's set up a variable that will hold a bool value of whether to load the external script or not. Since in this example I'm loading Prism, we will check to see if the page contains any code tags:

const loadScript = document.querySelector('pre,code');

if (loadScript === null) { return; }

Here, we only need to use the querySelector instead of querySelectorAll for a couple reasons:

  1. First, if there's at least one tag, then we should load the script.

  2. Second, if there are no tags on the page, the latter will return an empty Array, whereas the former will return null. It doesn't really matter, but the first is faster and easier to check against (in my opinion). Next, if the check for any pre or code tags returns null, let's exit out of the function immediately, since there will be no need to load the external script. Here you can see the performance benefit: since no checked-for tags are on the page, we can avoid loading unnecessary files (start happy dance)! If the page does have code on it, however, then we need to appropriately load that information into the DOM. A quick note: there are a few ways to go about this next step. You could load the script immediately and be fine. In effect, it would be synonymous with loading a script in the footer of your page. However, if you want to achieve a more asynchronous feel (i.e. running the script after everything has rendered, not actually async loading), then you can load the script after the Window's load event, which is what I do currently on my theme. Either way is fine, it's more up to how it "feels" for you. With that out of the way, let's create our script tag and inject it into the DOM:

    // Our new external script. const prismScript = document.createElement('script'); prismScript.src = '/wp-content/themes/calvinkoepke-com/build/js/prism.min.js'; prismScript.type = 'text/javascript';

    // Inject after the Window's load event. window.addEventListener('load', () => {  document.body.appendChild(prismScript); });

The Full Script

That's it! For reference, here is the entire code:

(function checker() => {

// Full loader script.
 document.addEventListener('DOMContentLoaded', () => {

  // Check if we should load or exit.
  const loadScript = document.querySelector('pre,code');
  if (loadScript === null) { return; }

  // Our new external script.
  const prismScript = document.createElement('script');
  prismScript.src = '/wp-content/themes/calvinkoepke-com/build/js/prism.min.js';
  prismScript.type = 'text/javascript';

  // Inject after the Window's load event.
  window.addEventListener('load', () => {



To Print or to Call Our Script

This is extra-curricular, but let's talk for a second about how to load our "checker" script on the page. This can be accomplished a couple of ways. If your hosting provider does not support HTTP/2 (or your average visitor uses a non-supporting browser), then you may want to cut down on the HTTP request by simply printing the script at the bottom of your page. However, seeing as how this can be a security vulnerability, it's much preferred to load it via a traditional <script src="/path/to/checker.js"> tag. Another option is to bundle the script into a more global JavaScript file that will be loaded on every page ( this is what I do). I hope this tutorial on how to load JavaScript dynamically made sense — please let me know in the comments if you have any questions. I'll do my best to answer or explain what I know!