Skip to content

Instantly share code, notes, and snippets.

@alexzuza
Created October 30, 2018 15:42
Show Gist options
  • Save alexzuza/55f1c7567a0fede48403a5a791661bb7 to your computer and use it in GitHub Desktop.
Save alexzuza/55f1c7567a0fede48403a5a791661bb7 to your computer and use it in GitHub Desktop.
Load script on demand
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
Copy link

bhaidar commented Nov 12, 2018

Hello,
Why have you chosen to use ReplaySubject instead of BehaviorSubject? Thanks

@alexzuza
Copy link
Author

alexzuza commented Nov 20, 2018

@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

@bhaidar
Copy link

bhaidar commented Nov 21, 2018

@alexzuza Wow nice observation :-) Thanks buddy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment