Profile image

Uche's Coding Corner

Passionate about software, technology, personal discoveries, and more.

How to add JavaScript to a page

Mon Feb 11 2019 🍵 0 min read

How and where you load external scripts on a page can affect page load speed and performance. <script> tags were usually placed in the <head> section and quite often without only the src attributes. These external Scripts are loaded and executed synchronously, meaning the HTML parser is forced to wait for the resource to be fetched. If there is an issue with the server response, this could result in page blocking and a terrible user experience. In order to avoid this, it is recommended to defer javascript loading and execution until the page is rendered.

One common solution is to place the <script> tag at the end of the <body> tag to ensure that the DOM is loaded first before executing any javascript. However, there are other equally good solutions.

aysnc and defer attributes

The <script> tags are placed in the <head> section with attributes async or defer. These attributes tell the browser how to fetch and execute external scripts.

The defer attribute tells the browser to load the script but not execute any Javascript until the DOM is ready (the document has been fully parsed and before the DOMContentLoaded event is fired).

<script src="https://" defer></script>

The async attribute tells the browser to execute the external script asynchronously. The HTML parser can continue parsing the page without waiting for the script to be executed.

<script src="https://" async></script>

Check caniuse.com for browser compatibility of async and defer attributes.

Dynamic insert

There are some cases where you only want to load a script in certain situations. This is known as on-demand loading to avoid unnecessary requests.

function insertScript(id, callback) {
  if (document.getElementById(id)) {
    return;
  }

  var scriptInDoc = document.getElementsByTagName('script')[0];
  var script = document.createElement('script');
  script.src = 'https://....';
  script.id = id;
  script.onload = function() {
    callback();
  }
  scriptInDoc.parentNode.insertBefore(script, scriptInDoc);
}

Conclusion

Always incorporate JavaScript asynchronously and only load external scripts at the point when they are needed to avoid extra network requests.

javascript
html
performance