Skip to content

Instantly share code, notes, and snippets.

@yussan
Last active October 6, 2021 13:21
Show Gist options
  • Save yussan/93947391fa88391218b4804e759396e9 to your computer and use it in GitHub Desktop.
Save yussan/93947391fa88391218b4804e759396e9 to your computer and use it in GitHub Desktop.
Async load external CSS using JS
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