javascript - 我是否需要删除或删除我创建但未附加到 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
好吗?有没有更优雅的方式?
解决方案
一旦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
)
推荐阅读
- python - 在具有分类变量和连续变量的高维数据集上使用凝聚层次聚类
- javascript - 重新运行将 Google Sheet 数据注入 Google 幻灯片的脚本时,如何清除所有现有数据?
- javascript - 如何修复 Node JS 错误在 heroku 上找不到模块“express”?
- javascript - 火库!如何通过 javascript 代码从数组中删除地图?
- python-3.x - RuntimeError:b'在初始化列表中没有参数'与pyproj geopandas
- visual-studio-2019 - 如何在 Visual Studio 2019 中的所有文件(甚至关闭的文件)上运行 ESLint
- haskell - 如何在haskell中获取数字的一部分
- ios - Swift - 如何按文本长度设置自定义视图
- javascript - 是否可以在 php 中包含 javascript 函数调用?
- c++ - 如何以编程方式清除 Windows 上的内部 Google Chrome DNS 缓存?