Skip to content

Instantly share code, notes, and snippets.

@thaliaarchi
Created October 10, 2016 02:29
Show Gist options
  • Save thaliaarchi/6aae8d8295d4bcf9c89c4150e33be3a9 to your computer and use it in GitHub Desktop.
Save thaliaarchi/6aae8d8295d4bcf9c89c4150e33be3a9 to your computer and use it in GitHub Desktop.
Load multiple scripts asynchronously in javascript
loadScripts([
'https://cdnjs.cloudflare.com/ajax/libs/tinycolor/1.4.1/tinycolor.min.js',
'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'
], () => {
console.log('Scripts loaded');
let color = tinycolor('hsl(207, 95%, 44%)');
console.log(color);
$('body').css('background-color', color.toHexString());
});
function loadScript(url: string, callback: Function) {
let script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
document.head.appendChild(script);
}
function loadScripts(urls: string[], callback: Function) {
let loadedCount = 0;
let multiCallback = () => {
loadedCount++;
if (loadedCount >= urls.length) {
callback.call(this, arguments);
}
};
for (let url of urls) {
loadScript(url, multiCallback);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment