javascript - Angular 6 - 在组件级别添加脚本并检查它是否存在
问题描述
我有一个脚本,我只想在一个组件上运行。我已经设法在组件上添加脚本,但是发生了一些我不完全确定如何解决的事情。
- 如果我导航到组件,脚本会添加到 DOM,但不会触发。如果我刷新页面,它可以工作
- 如果我导航到另一个组件并返回,则会再次添加脚本,并且它可以继续构建
组件.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?
在 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() {
}
}
推荐阅读
- android - Android Launcher:允许触摸通过动态壁纸
- postgresql - 如何在 PostgreSQL 中增量刷新物化视图,即仅针对新的或已更改的数据?
- excel - VBA:下标超出范围错误:For循环:多个工作表-表创建
- terraform - Terraform:depends_on 参数不首先创建指定的资源
- javascript - 谷歌图表时间线 - 个别颜色显示不准确
- go - 指针接收器和非指针接收器的数据竞争差异
- django - 我正在制作一个 User(AbsrtactUser) 模型,我需要创建一个自动递增的字段
- r - R中不同分组的分组线性回归预测
- c# - 如何保存/传递 MongoDB UpdateDefinition 以进行日志记录和以后使用?
- python - 如何在python中绘制饼图?