Created
May 3, 2018 03:38
-
-
Save googlicius/e07b6ce82a8020ccc809a17955b85213 to your computer and use it in GitHub Desktop.
This file contains 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
// 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