SVG 符号不会触发加载事件(仅在 Firefox 中).我寻找解决方法

SVG symbols do not fire onload event (only in firefox). I look for a workaround

本文关键字:Firefox 寻找 方法 解决 仅在 符号 事件 加载 SVG      更新时间:2023-09-26

我正在一个项目中使用 D3.js 使用 SVG 制作图表。该图使用 SVG 符号。我有javascript代码来管理带有onload事件的这些项目。

在诸如webkit引擎之类的浏览器中,浏览器运行得非常好。但是火狐...Firefox 不会在 SVG 中运行任何加载事件。

好吧,我看到了这个错误,并认为Firefox是自由软件,这些人喜欢错误跟踪。我已经上传了错误 https://bugzilla.mozilla.org/show_bug.cgi?id=1254159。

这些人的反应是"不会修复"。

检查错误的示例很小且清晰:

<html>
    <head>
        <title>test onload event in a svg symbol</title>
        <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
    </head>
    <body>
        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" pointer-events="all" width="500px" height="500px" style="background: #ffff00;">
            <g class="cat" transform="translate(100 100)">
                <use xlink:href="animals.svg#cat" onload="javascript: console.log('This message is not showed in firefox.');" />
            </g>
        </svg>
        <script type="text/javascript">
            d3.select("svg")
                .append("g")
                    .attr("class", "dog")
                    .attr("transform", "translate(200 200) scale(0.5)")
                    .append("use")
                        .attr("xlink:href", "animals.svg#dog")
                        .on("load", function() {
                            console.log("And this message is not showed in firefox too.");
                        });
        </script>
    </body>
</html>

最后,我在 w3c 文档中查找,符号中的事件加载是标准的:https://www.w3.org/TR/SVG/struct.html#UseElement

有人对此有解决方法吗?

解决这个问题的很长的方法是自己处理外部资源的加载(或者更确切地说,在 d3 的帮助下)。

D3 有一个 xml 加载程序函数 (https://github.com/mbostock/d3/wiki/Requests#d3_xml),svg 是 xml,因此您可以执行以下操作:

  • 准备不使用外部资源的内容
  • 使用 D3 加载 SVG
  • 在 D3.xml 的回调函数中,你得到一个 DOML 元素:将其插入图形中的相关位置,并执行在 "onload" 事件中要做的任何工作。

(可能有一个更简单的方法,我只是不知道)