File
Constructor
constructor(_document: any)
|
|
Parameters :
Name |
Type |
Optional |
_document |
any
|
No
|
|
Methods
Public
load
|
load(url: string)
|
|
Parameters :
Name |
Type |
Optional |
url |
string
|
No
|
Returns : Promise<void>
|
Private
removeRequest
|
removeRequest(url: string)
|
|
Parameters :
Name |
Type |
Optional |
url |
string
|
No
|
|
Private
scriptExist
|
scriptExist(url: string)
|
|
Parameters :
Name |
Type |
Optional |
url |
string
|
No
|
|
Private
validateRequestExists
|
validateRequestExists(url: string)
|
|
Parameters :
Name |
Type |
Optional |
url |
string
|
No
|
Returns : Promise | null
|
Private
_queue
|
Type : literal type[]
|
|
import {Inject, Injectable} from '@angular/core';
import {DOCUMENT} from '@angular/common';
@Injectable()
export class LazyLoadService {
private _queue: {
promise: Promise<void>,
id: string
}[];
constructor(
@Inject(DOCUMENT) private _document: any
) {
this._queue = [];
}
public load(url: string): Promise<void> {
let request = this.validateRequestExists(url);
if (!request) {
request = new Promise<void>((resolve, reject) => {
if (this.scriptExist(url)) {
resolve();
return;
}
const onLoad = () => {
this.removeRequest(url);
resolve();
};
const onError = () => {
this.removeRequest(url);
reject();
};
const script = this._document.createElement('script') as HTMLScriptElement;
script.type = 'text/javascript';
script.src = url;
script.id = url;
script.crossOrigin = 'anonymous';
script.onload = onLoad;
script.onerror = onError;
this._document.body.appendChild(script);
});
this._queue.push({
promise: request,
id: url
});
}
return request;
}
private scriptExist(url: string): boolean {
return this._document.getElementById(url) !== null;
}
private validateRequestExists(url: string): Promise<void> | null {
let result = null;
this._queue.forEach(request => {
if (request.id === url) {
result = request.promise;
}
});
return result;
}
private removeRequest(url: string): void {
let i = -1;
this._queue.forEach((request, index) => {
if (request.id === url) {
i = index;
}
});
if (i > -1) {
this._queue.splice(i, 1);
}
}
}