首页 > 解决方案 > Angular 6 - 在组件级别添加脚本并检查它是否存在

问题描述

我有一个脚本,我只想在一个组件上运行。我已经设法在组件上添加脚本,但是发生了一些我不完全确定如何解决的事情。

  1. 如果我导航到组件,脚本会添加到 DOM,但不会触发。如果我刷新页面,它可以工作
  2. 如果我导航到另一个组件并返回,则会再次添加脚本,并且它可以继续构建

组件.ts

import { Component, OnInit } from '@angular/core';
import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

@Component({
  selector: 'app-privacy',
  templateUrl: './privacy.component.html',
  styles: []
})
export class PrivacyComponent implements OnInit {

  constructor(private _renderer2: Renderer2, @Inject(DOCUMENT) private _document) {
    let s = this._renderer2.createElement('script');
    s.type = `text/javascript`;
    s.src = `../../assets/scripts/privacy.js`;

    this._renderer2.appendChild(this._document.body, s);
   }

  ngOnInit() {
  }

}

标签: javascriptangularexternal-script

解决方案


您需要将onload(如果您需要支持 IE 确保也支持onreadystatechange)处理程序添加到您的脚本元素中,该处理程序可以在脚本完成加载时调用您想要执行的函数。

要删除 onNgDestroy 脚本,请createElement?在 Component 上保存一个引用,并在 Destroy 生命周期挂钩中删除它。

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

@Component({
  selector: 'app-privacy',
  templateUrl: './privacy.component.html',
  styles: []
})
export class PrivacyComponent implements OnInit, OnDestroy {
  private s: any;
  constructor(private _renderer2: Renderer2, @Inject(DOCUMENT) private _document) {
    this.s = this._renderer2.createElement('script');
    this.s.type = `text/javascript`;
    this.s.src = `../../assets/scripts/privacy.js`;
    this.s.onload = this.doneLoading;

    this._renderer2.appendChild(this._document.body, this.s);
  }

  doneLoading () {
    // do what you need to do
  }


  ngOnDestroy() {
    // this removes the script so it won't be added again when the component gets initialized again.
    this._renderer2.removeChild(this._document.body, this.s)
  }

  ngOnInit() {
  }

}

推荐阅读