Skip to content

Instantly share code, notes, and snippets.

@cheshirecode
Last active May 24, 2022 11:47
Show Gist options
  • Save cheshirecode/9acb5d4fdd7945074edfa4554121aa6c to your computer and use it in GitHub Desktop.
Save cheshirecode/9acb5d4fdd7945074edfa4554121aa6c to your computer and use it in GitHub Desktop.
2 ways to dynamically load scripts in JavaScript
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);
}
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