Skip to content

Instantly share code, notes, and snippets.

@jpzwarte
Created August 23, 2019 07:27
Show Gist options
  • Save jpzwarte/e4b320a760e306df093f852771179aff to your computer and use it in GitHub Desktop.
Save jpzwarte/e4b320a760e306df093f852771179aff to your computer and use it in GitHub Desktop.
constructor(@Inject(DOCUMENT) private document: any) {
this.style = this.document.createElement('style');
this.style.id = 'theme';
this.document.head.appendChild(this.style);
}
initialize(): Promise<void> {
this._theme = 'magister';
return this.loadTheme(this._theme);
}
private async loadTheme(id: string) {
if (environment.production) {
return this.loadStylesheet(id);
} else if (this.cache.has(id)) {
this.style.innerHTML = this.cache.get(id);
} else {
return this.loadScript(id);
}
}
private async loadScript(id: string) {
const script = this.document.createElement('script');
script.src = `/${id}.js`;
script.onload = () => {
const style = this.document.head.lastChild as HTMLStyleElement;
this.cache.set(id, style.innerHTML);
this.style.innerHTML = style.innerHTML;
this.document.head.removeChild(script);
this.document.head.removeChild(style);
};
this.document.head.appendChild(script);
}
private async loadStylesheet(id: string) {
if (!this.link) {
this.link = this.document.createElement('link');
this.link.rel = 'stylesheet';
}
this.link.href = `/${id}.css`;
this.document.head.appendChild(this.link);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment