Angular应用程序被销毁时,导入的脚本未从内存中清除。
创始人
2024-10-30 13:00:40
0

在 Angular 应用程序的销毁钩子中手动清除导入的脚本。以下是一个示例:

import { Component, OnDestroy } from '@angular/core';
import { ScriptService } from './script.service';

@Component({
  selector: 'app-root',
  template: '

Hello World

', }) export class AppComponent implements OnDestroy { constructor(private scriptService: ScriptService) {} ngOnDestroy() { this.scriptService.destroy(); } }

在上面的示例中,AppComponent 实现了 OnDestroy 接口,并在其 ngOnDestroy 生命周期钩子中调用 ScriptService 的 destroy() 方法。ScriptService 中包含了逻辑来清理所导入的脚本。要创建 ScriptService,请使用以下代码:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class ScriptService {
  private scripts: any = {};

  constructor() {}

  load(...scripts: string[]) {
    const promises = [];
    scripts.forEach((url) => {
      if (!this.scripts[url]) {
        this.scripts[url] = this.loadScript(url);
        promises.push(this.scripts[url]);
      }
    });
    return Promise.all(promises);
  }

  loadScript(url: string): Promise {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = url;

      script.onload = () => {
        resolve();
      };

      script.onerror = (error: any) => {
        reject(error);
      };

      document.body.appendChild(script);
    });
  }

  destroy() {
    const scripts = document.getElementsByTagName('script');
    for (let i = 0; i < scripts.length; i++) {
      const script = scripts[i];
      const src = script.getAttribute('src');
      if (src && this.scripts[src]) {
        script.remove();
        delete this.scripts[src];
      }
    }
  }
}

在上面的示例中,ScriptService 包含了 load() 方法,用于加载脚本,并且包含了 destroy()

相关内容

热门资讯

这一现象值得深思!wepoke... 这一现象值得深思!wepoker智能辅助插件,wejoker私人辅助软件(透视)辅助教程(有挂神器)...
透视app!wepoker免费... 透视app!wepoker免费辅助器,sohoo辅助(透视)开挂教程(有挂教程)-哔哩哔哩1)wep...
此事备受玩家关注!hhpoke... 此事备受玩家关注!hhpoker德州挂真的有吗,wepoker怎么设置透视(透视)有挂教程(确实有挂...
透视ai代打!wpk透视工作室... 您好,竞技联盟破解版最新版这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很...
透视神器!pokemmo辅助器... 透视神器!pokemmo辅助器手机版下载,wepoker辅助是真的假的(透视)揭幕教程(有挂方式)-...
据了解!拱趴大菠萝有什么挂,w... 据了解!拱趴大菠萝有什么挂,wepoker有人用过吗(透视)专业教程(证实有挂)-哔哩哔哩1、进入游...
透视辅助!wepoker辅助透... 透视辅助!wepoker辅助透视软件,hhpoker必备开挂(透视)详细教程(证实有挂)-哔哩哔哩1...
长期以来!we poker游戏... 长期以来!we poker游戏下,智星德州插件(透视)详细教程(有挂方式)-哔哩哔哩1)智星德州插件...
透视app!werplan脚本... 透视app!werplan脚本,aapoker透视插件(透视)总结教程(有挂规律)-哔哩哔哩1、全新...
现有关情况通报如下!hhpok... 现有关情况通报如下!hhpoker辅助挂是真的吗,wepoker免费透视脚本(透视)解谜教程(果真有...