繁体   English   中英

是否需要删除或删除创建但未附加到DOM的HTML元素?

[英]Do I need to remove or delete HTML elements that I created but didn't attach to the DOM?

我正在实现一些我的(高级)图表的客户端下载。 我现在正在做的是获取图表的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);

现在下载可以正常工作,但是看来我创建的canvas元素c已附加到窗口中,甚至在下载完成后也可以粘贴。

调用c.remove()没有帮助。 c.parentNodec.parentElement为null(显然是因为我没有将c附加到DOM),所以我无法在任何对象上调用removeChild(c)

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

一旦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在周围)

是的,上一个答案是正确的,但您也可以通过设置画布的最小尺寸来清除画布

(() => {
     var c = document.createElement("canvas");
      canvg(c, file);
      c.toBlob(function (blob) {
              saveAs(blob, fileName);
              c.width = c.height = 0;
      }, contentType, 1); 
})()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM