Last active
October 6, 2021 13:21
-
-
Save yussan/93947391fa88391218b4804e759396e9 to your computer and use it in GitHub Desktop.
Async load external CSS using JS
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
export default function loadCSS(href: string, cb: Function | null) { | |
if(!isStyleLoaded(href)) { | |
const l: HTMLElement | null = document.createElement('link') | |
l.setAttribute('rel', 'stylesheet') | |
l.setAttribute('href', href) | |
if(cb) | |
l.onload = cb() | |
document.body.appendChild(l) | |
} | |
} | |
//check is style loaded | |
function isStyleLoaded(href: string) { | |
const styles: any = document.querySelectorAll('link[rel=\'stylesheet\']') | |
// is css loaded | |
for (let i = styles.length; i--;) { | |
if(styles[i].href == href) return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment