How to load external scripts dynamically in Angular?

前端 未结 15 950
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:48

I have this module which componentize the external library together with additional logic without adding the

15条回答
  •  遥遥无期
    2020-11-22 07:22

    import { Injectable } from '@angular/core';
    import * as $ from 'jquery';
    
    interface Script {
        src: string;
        loaded: boolean;
    }
    
    @Injectable()
    export class ScriptLoaderService {
        public _scripts: Script[] = [];
    
        /**
         * @deprecated
         * @param tag
         * @param {string} scripts
         * @returns {Promise}
         */
        load(tag, ...scripts: string[]) {
            scripts.forEach((src: string) => {
                if (!this._scripts[src]) {
                    this._scripts[src] = { src: src, loaded: false };
                }
            });
    
            const promises: any[] = [];
            scripts.forEach(src => promises.push(this.loadScript(tag, src)));
    
            return Promise.all(promises);
        }
    
        /**
         * Lazy load list of scripts
         * @param tag
         * @param scripts
         * @param loadOnce
         * @returns {Promise}
         */
        loadScripts(tag, scripts, loadOnce?: boolean) {
            debugger;
            loadOnce = loadOnce || false;
    
            scripts.forEach((script: string) => {
                if (!this._scripts[script]) {
                    this._scripts[script] = { src: script, loaded: false };
                }
            });
    
            const promises: any[] = [];
            scripts.forEach(script => promises.push(this.loadScript(tag, script, loadOnce)));
    
            return Promise.all(promises);
        }
    
        /**
         * Lazy load a single script
         * @param tag
         * @param {string} src
         * @param loadOnce
         * @returns {Promise}
         */
        loadScript(tag, src: string, loadOnce?: boolean) {
            debugger;
            loadOnce = loadOnce || false;
    
            if (!this._scripts[src]) {
                this._scripts[src] = { src: src, loaded: false };
            }
    
            return new Promise((resolve, _reject) => {
                // resolve if already loaded
                if (this._scripts[src].loaded && loadOnce) {
                    resolve({ src: src, loaded: true });
                } else {
                    // load script tag
                    const scriptTag = $('
    
                                     
                  
提交回复
热议问题