gpt4 book ai didi

javascript - Angular 6 - 在组件级别添加脚本并检查它是否存在

转载 作者:太空狗 更新时间:2023-10-29 18:35:32 25 4
gpt4 key购买 nike

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

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

component.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() {
}

}

最佳答案

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

要删除 onNgDestroy 脚本,请在组件上保存 createElement? 的引用,并在 Destroy 生命周期 Hook 中删除它。

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() {
}

}

关于javascript - Angular 6 - 在组件级别添加脚本并检查它是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55263567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com