JS

HOW TO DYNAMICALLY LOAD JAVASCRIPT

CREATE NEW <SCRIPT> TAG var js = document.createElement("script"); js.src = "SCRIPT.JS";

CREATE SCRIPT TAG

01

OPTIONAL - ON LOAD & ERROR js.onload = () => { alert("Loaded"); }; js.onerror = (e) => { alert("Error"); };

APPEND <SCRIPT> TAG TO <HEAD> document.head.appendChild(js);

CREATE NEW <SCRIPT> TAG var js = document.createElement("script"); js.textContent = `function demo ()  { alert("It works!"); }`;

JS TO CREATE JS

02

INSERT <SCRIPT> TAG TO <HEAD> document.head.appendChild(js);

fetch("SCRIPT.JS") .then(res => res.text())  .then(txt => {   CREATE NEW <SCRIPT> TAG   var js = document.createElement("script");   js.textContent = txt;   APPEND <SCRIPT> TAG TO <HEAD>   document.head.appendChild(js);  });

AJAX LOAD JAVASCRIPT

03

* DONT' DO THIS. JUST CREATE A <SCRIPT ASYNC SRC="SCRIPT.JS">.