簡體   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