How to Add Script to Head in JavaScript – Dynamic Injection

When dealing with external libraries and files in your JavaScript header, there are situations where one needs to dynamically add a script. If the script that needs to be added relies on another dependency in the header this should be avoided to not cause a reference error.

However, other situations call for dynamic injection, so how can you add a script to the head in JavaScript? This is done by using document.createElement.

const script = document.createElement("script");
script.type = "text/javascript";
script.src = "url";

document.head.appendChild(script);
  • We have created a script element using createElement()
  • Assigned its type and src properties dynamically
  • And subsequently used appendChild() to attach it to the document.head

And there you have is, a dynamically injected script!

Proudly published with Gatsby