Skip to content

Instantly share code, notes, and snippets.

@Klemek
Last active July 17, 2019 17:21
Show Gist options
  • Save Klemek/6f02924ff348c6e61c387bc8406beb41 to your computer and use it in GitHub Desktop.
Save Klemek/6f02924ff348c6e61c387bc8406beb41 to your computer and use it in GitHub Desktop.
Github script loading
const github = (repo) => {
const self = {
loadScript: (file) => new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', `https://raw.githubusercontent.com/${repo}/master/${file}`);
xhr.onload = function() {
if (xhr.status === 200) {
const u = URL.createObjectURL(new Blob([xhr.responseText], { type: 'text/javascript' }));
const s = document.createElement('script');
s.src = u;
s.onload = resolve;
s.onerror = reject;
document.body.appendChild(s);
document.body.removeChild(s);
URL.revokeObjectURL(u);
}else
reject();
};
xhr.send();
}),
loadScripts: (...files) => new Promise((resolve, reject) => {
if(!files || !files.length)
return resolve();
self.loadScript(files.splice(0, 1)).then(() => {
self.loadScripts(...files).then(resolve);
}).catch(reject);
})
};
return self;
};

Load script with

<script src="github-cdn.js"></script>

Then use with :

// one script
github('klemek/fa-diagrams').loadScript('dist/fa-diagrams-data.min.js').then(...).catch(...);

// several files
github('klemek/fa-diagrams').loadScripts('dist/fa-diagrams-data.min.js', 'dist/fa-diagrams.min.js').then(...).catch(...);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment