![](/img/trans.png)
[英]Do i need to delete dom fragments or will the garbage collector remove them?
[英]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.parentNode
和c.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.