Last active
February 2, 2021 16:59
-
-
Save TomasKostadinov/d0b3d4aeff2bfa2462e2b88b479b91cd to your computer and use it in GitHub Desktop.
Load Stylesheets in Angular Asynchronously
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
export async function loadStyleSheets(items: StyleSheetLoadingItem[]) { | |
items.forEach((item) => { | |
loadStyleSheet(item.stylePath, item.elementName); | |
}); | |
} | |
async function loadStyleSheet(styleModule: Promise<{ default: string }>, elementName: string = '') { | |
// Import style if not already done | |
if (document.getElementById(elementName) == null) { | |
// @ts-ignore | |
const fileStyle = await styleModule; | |
const styleElement = document.createElement('style'); | |
styleElement.id = elementName; | |
styleElement.appendChild(document.createTextNode( | |
fileStyle.default | |
)); | |
document.head.appendChild(styleElement); | |
} | |
} | |
export interface StyleSheetLoadingItem { | |
stylePath: Promise<{ default: string }>; | |
elementName: string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment