Angular中通过Script ID移除DOM脚本标签的正确方法(解决forEach报错)
解决Angular子组件添加/移除多个Script标签的问题
原代码的问题点
- 生命周期钩子拼写错误:
ngonOnInit应为ngOnInit,ngDestroy应为ngOnDestroy(Angular钩子函数首字母需大写) - 仅创建了1个script标签,但需求是添加3个
- 销毁时用
getElementById获取的是单个DOM元素,并非集合,因此无法调用forEach - 依赖DOM查找元素不够可靠,推荐直接保存组件内创建的元素引用
正确实现方案
在组件类中维护一个数组,专门存储创建的script标签实例,销毁时直接遍历这个数组移除元素,无需从DOM中查找,更高效可靠:
import { Component, Input, OnInit, OnDestroy } from '@angular/core'; @Component({ selector: 'child', template: '' // 子组件模板根据实际需求编写 }) export class ChildComponent implements OnInit, OnDestroy { @Input() id!: string; // 存储创建的script标签实例 private scriptElements: HTMLScriptElement[] = []; ngOnInit(): void { // 循环创建3个script标签 for (let i = 0; i < 3; i++) { const scriptTag = document.createElement('script'); // 给每个script设置唯一id,避免冲突 scriptTag.id = `${this.id}-script-${i}`; // 可按需设置script的src或其他属性,例如: // scriptTag.src = 'your-target-script-url'; // scriptTag.async = true; document.body.appendChild(scriptTag); // 将创建的元素存入数组 this.scriptElements.push(scriptTag); } } ngOnDestroy(): void { // 遍历数组,逐个移除script标签 this.scriptElements.forEach(script => { script.remove(); }); // 清空数组,避免内存泄漏 this.scriptElements = []; } }
代码说明
- 维护元素引用数组:
scriptElements数组保存所有创建的script标签,后续销毁操作直接使用这些引用,无需DOM查询 - 唯一ID设置:通过
${this.id}-script-${i}给每个script生成唯一ID,避免和其他元素冲突 - 正确的生命周期钩子:使用
ngOnInit和ngOnDestroy(注意首字母大写),确保钩子函数被Angular正确调用 - 清理内存:移除元素后清空数组,避免不必要的内存占用
内容的提问来源于stack exchange,提问作者Yami
相关产品推荐
相关产品推荐

