首页 > 解决方案 > 我是否需要删除或删除我创建但未附加到 DOM 的 HTML 元素?

问题描述

我正在实现我拥有的一些(高)图表的客户端下载。我现在正在做的是获取图表的 SVG 源,创建一个“画布”元素并将 SVG 绘制到所述元素,然后使用 toBlob/Filesaver.js 下载图像。请参见下面的代码:

// draw the svg to a canvas
var c = document.createElement("canvas");
canvg(c, file);

// scrape the image from the canvas as png or jpg and download it in full quality
c.toBlob(function (blob) {
  saveAs(blob, fileName);
}, contentType, 1);

现在下载工作正常,但似乎我创建的画布元素c, 已附加到窗口并且即使在下载完成后仍然存在。

打电话c.remove()也没用。c.parentNode并且c.parentElement是空的(显然因为我没有附加c到 DOM)所以我不能调用removeChild(c)任何东西。

我想知道如何删除/删除元素c?够c = undefined/null好吗?有没有更优雅的方式?

标签: javascripthtmldomcanvg

解决方案


一旦c超出范围,它应该自动收集垃圾,只要canvg不保留对它的不必要的引用。

为确保c最终不再可引用,请将整个代码放入 IIFE:

(() => {
  // draw the svg to a canvas
  var c = document.createElement("canvas");
  canvg(c, file);

  // scrape the image from the canvas as png or jpg and download it in full quality
  c.toBlob(function (blob) {
    saveAs(blob, fileName);
  }, contentType, 1);
})();

(否则,它会一直保留为window.c


推荐阅读