How to load external scripts dynamically in Angular?

前端 未结 15 752
被撕碎了的回忆
被撕碎了的回忆 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:00

    An Angular universal solution; I needed to wait for a particular element to be on the page before loading a script to play a video.

    import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
    import {isPlatformBrowser} from "@angular/common";
    
    @Injectable({
      providedIn: 'root'
    })
    export class ScriptLoaderService {
    
      constructor(
        @Inject(PLATFORM_ID) private platformId: Object,
      ) {
      }
    
      load(scriptUrl: string) {
        if (isPlatformBrowser(this.platformId)) {
          let node: any = document.createElement('script');
          node.src = scriptUrl;
          node.type = 'text/javascript';
          node.async = true;
          node.charset = 'utf-8';
          document.getElementsByTagName('head')[0].appendChild(node);
        }
      }
    }
    

提交回复
热议问题