Skip to content

Instantly share code, notes, and snippets.

@TomasKostadinov
Last active February 2, 2021 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TomasKostadinov/d0b3d4aeff2bfa2462e2b88b479b91cd to your computer and use it in GitHub Desktop.
Save TomasKostadinov/d0b3d4aeff2bfa2462e2b88b479b91cd to your computer and use it in GitHub Desktop.
Load Stylesheets in Angular Asynchronously
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