Last active
April 1, 2021 14:37
-
-
Save crazy4groovy/d7877581ed23dfe17aa7528d0d403f99 to your computer and use it in GitHub Desktop.
Dynamically load a script text or URL (JavaScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// see: https://tinyurl.com/yxtf55bn | |
function loadScript(id, innerHTML) { | |
var script = document.createElement("script"); | |
script.type = "text/javascript"; | |
script.id = id || Math.random().toString().substr(2); | |
script.innerHTML = innerHTML; | |
document.body.appendChild(script); | |
} | |
// load script text | |
loadScript(null, "\ | |
console.log('Script text loaded!');\ | |
console.log('This is second console.');\ | |
"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function loadScriptByURL(id, url) { | |
return new Promise(function(resolve) { | |
var isScriptExist = document.getElementById(id); | |
if (isScriptExist) { | |
return resolve(); | |
} | |
var script = document.createElement("script"); | |
script.type = "text/javascript"; | |
script.src = url; | |
script.id = id; | |
script.onload = resolve; | |
document.body.appendChild(script); | |
}); | |
} | |
// load the script by passing the URL | |
loadScriptByURL("script-id", "<PATH_OF_SCRIPT_URL>") | |
.then(function() { | |
console.log("Script URL loaded!"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment