Last active
May 24, 2022 11:47
-
-
Save cheshirecode/9acb5d4fdd7945074edfa4554121aa6c to your computer and use it in GitHub Desktop.
2 ways to dynamically load scripts in 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
export default (source) => { | |
source || return; | |
const newScript = document.createElement("script"); | |
newScript.async = true; | |
newScript.src = source; | |
const s0 = document.getElementsByTagName('script')[0]; | |
s0.parentNode.insertBefore(newScript, s0); | |
} |
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
export default ({ id, src, onLoad, d = document, s = 'script' }) => { | |
if (d.getElementById(id)) { | |
return; | |
} | |
const js = d.createElement(s); | |
js.id = id; | |
if (onLoad) { | |
js.onload = onLoad; | |
} | |
js.src = src; | |
js.async = true; | |
js.defer = true; | |
const scripts = d.getElementsByTagName(s)[0]; | |
if (scripts) { | |
scripts.parentNode.insertBefore(js, scripts); | |
} else { | |
document.body.appendChild(js); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment