Load new script dynamically via JavaScript

Function JavaScript 1 revisions 104 a year ago a year ago
function loadScript(src) {
	let firstScript = document.getElementsByTagName('script')[0];
	let scriptNode;

	return new Promise((resolve, reject) => {
		scriptNode = document.createElement('script');
		scriptNode.async = 1;
		scriptNode.src = src;

		scriptNode.onload = () => resolve();
		scriptNode.onerror = () => reject(new Error(`failed to load: ${src}`));

		firstScript.parentNode.insertBefore(scriptNode, firstScript);

This function loads a script dynamically via JavaScript. A good usage of this is when you, for example, want to load Google's reCAPTCHA script when a user opens a form dynamically or something.



This adds to the <head> element:

<script async="" src="https://www.google.com/recaptcha/api.js"></script>