showing results for - "angular dynamic script loading"
Malina
09 Feb 2017
1import { Injectable } from "@angular/core";
2import { Observable } from "rxjs/Observable";
3import { Observer } from "rxjs/Observer";
4
5@Injectable()
6export class ScriptLoaderService {
7    private scripts: ScriptModel[] = [];
8
9    public load(script: ScriptModel): Observable<ScriptModel> {
10        return new Observable<ScriptModel>((observer: Observer<ScriptModel>) => {
11            var existingScript = this.scripts.find(s => s.name == script.name);
12
13            // Complete if already loaded
14            if (existingScript && existingScript.loaded) {
15                observer.next(existingScript);
16                observer.complete();
17            }
18            else {
19                // Add the script
20                this.scripts = [...this.scripts, script];
21
22                // Load the script
23                let scriptElement = document.createElement("script");
24                scriptElement.type = "text/javascript";
25                scriptElement.src = script.src;
26
27                scriptElement.onload = () => {
28                    script.loaded = true;
29                    observer.next(script);
30                    observer.complete();
31                };
32
33                scriptElement.onerror = (error: any) => {
34                    observer.error("Couldn't load script " + script.src);
35                };
36
37                document.getElementsByTagName('body')[0].appendChild(scriptElement);
38            }
39        });
40    }
41}
42
43export interface ScriptModel {
44    name: string,
45    src: string,
46    loaded: boolean
47}
48