Created
August 23, 2019 07:27
-
-
Save jpzwarte/e4b320a760e306df093f852771179aff to your computer and use it in GitHub Desktop.
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
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