Last active
September 4, 2017 12:22
-
-
Save willishq/cb7e1070eebae80b78916a929dfaff4a to your computer and use it in GitHub Desktop.
ES6 script loader
This file contains hidden or 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
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