[英]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.