Created
October 30, 2018 15:42
-
-
Save alexzuza/55f1c7567a0fede48403a5a791661bb7 to your computer and use it in GitHub Desktop.
Load script on demand
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
import { Injectable, Inject } from '@angular/core'; | |
import { ReplaySubject, Observable } from 'rxjs'; | |
import { DOCUMENT } from '@angular/common'; | |
@Injectable() | |
export class LazyLoadingScriptService { | |
_loadedLibraries: { [url: string]: ReplaySubject<any> } = {}; | |
constructor(@Inject(DOCUMENT) private readonly document: any) { } | |
loadScript(url: string): Observable<any> { | |
if (this._loadedLibraries[url]) { | |
return this._loadedLibraries[url].asObservable(); | |
} | |
this._loadedLibraries[url] = new ReplaySubject(); | |
const script = this.document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.src = url; | |
script.onload = () => { | |
this._loadedLibraries[url].next(); | |
this._loadedLibraries[url].complete(); | |
}; | |
this.document.body.appendChild(script); | |
return this._loadedLibraries[url].asObservable(); | |
} | |
} | |
/* Usage */ | |
this.lazyLoadService.loadScript('/assets/scripts/some-script.js').subscribe(() => { | |
// code | |
}); |
@bhaidar Hey! Because if we would use BehaviorSubject here then we would get additional subscription call before onload.
See also output in console here https://ng-run.com/edit/1gswCjJUKFImbulXetIv?open=app%2Fservice.ts
@alexzuza Wow nice observation :-) Thanks buddy
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello,
Why have you chosen to use ReplaySubject instead of BehaviorSubject? Thanks