Skip to content

Instantly share code, notes, and snippets.

@googlicius
Created May 3, 2018 03:38
Show Gist options
  • Save googlicius/e07b6ce82a8020ccc809a17955b85213 to your computer and use it in GitHub Desktop.
Save googlicius/e07b6ce82a8020ccc809a17955b85213 to your computer and use it in GitHub Desktop.
// Load CSS file async
export const loadAsyncCss = (href: string | Array<string>, id, cb: () => void = null) => {
function createElement(d, s, href) {
var link = d.createElement(s);
link.href = href;
link.rel = 'stylesheet';
return link;
}
(function (d, id, href, r) {
var fjs = d.getElementsByTagName('link')[0];
var promises: Array<Promise<any>> = [];
const ID_CSS = id + '-css';
if (d.getElementById(id) || d.getElementById(ID_CSS)) {
if (typeof r == 'function') {
r();
}
return;
}
if (typeof href == 'string') {
href = [href];
}
href.forEach((href_str, i) => {
var link = createElement(d, 'link', href_str);
if (i == href.length - 1) {
link.id = ID_CSS;
}
fjs.parentNode.insertBefore(link, fjs);
var promise = new Promise((resolve, reject) => {
link.onload = function () {
resolve();
}
});
promises.push(promise);
});
if (typeof r == 'function') {
Promise.all(promises).then(() => r());
}
}(document, id, href, cb));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment