If you want to lazy load external libraries such as jquery
, jspdf
you can create some service like:
lazy-loading-library.service.ts
import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { DOCUMENT } from '@angular/platform-browser';
@Injectable()
export class LazyLoadingLibraryService {
private loadedLibraries: { [url: string]: ReplaySubject<any> } = {};
constructor(@Inject(DOCUMENT) private readonly document: any) { }
public loadJs(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();
}
}
And whenever you need some external library just use this service that will load library only once:
app.component.ts
export class AppComponent {
constructor(private service: LazyLoadingLibraryService) {}
loadJQuery() {
this.service.loadJs('https://code.jquery.com/jquery-3.2.1.min.js').subscribe(() => {
console.log(`jQuery version ${jQuery.fn.jquery} has been loaded`);
});
}
loadJsPdf() {
this.service.loadJs('https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js').subscribe(() => {
console.log(`JsPdf library has been loaded`);
});
}
Plunker Example
If you're looking for lazy loading angular module then these questions might be helpful for you: