Skip to content

Instantly share code, notes, and snippets.

@fedecarg
Last active November 28, 2017 10:01
Show Gist options
  • Select an option

  • Save fedecarg/99d288be2d8a696967f1d3d2480ad26d to your computer and use it in GitHub Desktop.

Select an option

Save fedecarg/99d288be2d8a696967f1d3d2480ad26d to your computer and use it in GitHub Desktop.
Load scripts asynchronously
const loadScript = (uri) => {
return new Promise((resolve, reject) => {
const el = document.createElement('script');
el.type = 'text/javascript';
el.src = uri;
if (id) {
const docEl = document.getElementById(id);
if (docEl) {
docEl.parentNode.removeChild(docEl);
}
el.id = id;
}
el.onload = () => {
el.onload = el.onerror = null;
if (resolve) {
resolve();
}
};
el.onerror = () => {
el.onload = el.onerror = null;
if (reject) {
reject();
}
};
document.head.appendChild(el);
};
};
loadScript('http://path/to/script.js').then(
(data) => {
console.log('success');
console.log(data);
},
(error) => {
console.log(error);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment