Skip to content

Instantly share code, notes, and snippets.

@willishq
Last active September 4, 2017 12:22
Show Gist options
  • Save willishq/cb7e1070eebae80b78916a929dfaff4a to your computer and use it in GitHub Desktop.
Save willishq/cb7e1070eebae80b78916a929dfaff4a to your computer and use it in GitHub Desktop.
ES6 script loader
import qs from 'qs';
/*
loadScript('https://example.com/script.js').then(() => {
// do something
}).catch(e => console.log(e));
const loadjQuery = async () => {
try {
await loadscript('https://code.jquery.com/jquery-3.2.1.js');
// use jquery code
} catch (e) {
console.log(e);
}
}
*/
export const loadScript = (url, params) => new Promise((res, rej) => {
const script = document.createElement('script');
let realUrl = url;
script.onload = res;
script.onerror = rej;
if (typeof params !== 'undefined') {
realUrl += qs.stringify(params);
}
if (document.querySelectorAll(`[src="${realUrl}"]`).length === 0) {
script.src = realUrl;
document.body.appendChild(script);
} else {
res();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment