跳过包含 Internet Explorer 的 d3.js

我有一个使用最新版本的 d3 (v6) 的项目,我在我的 index.html 中包含如下 api:

        <script src="scripts/d3.js"></script>

此版本的 d3 不支持 IE,我收到控制台错误,因为 IE 中的 ECMA 版本的 Javascript 不支持 => 例如。

这对我来说很好,因为我测试是否window.d3存在,如果不存在,那么我会显示其他内容而不是我的 d3 图表。

但我不想出现这个控制台错误。

那么如果浏览器不是 IE,如何只包含 d3.js 呢?

谢谢


至尊宝的传说
浏览 79回答 1
1回答

慕仙森

您可以检查浏览器userAgent是否是IE,如果不是则加载d3脚本。您可以参考下面的代码,它运行良好并清除 IE 11 中的 d3 控制台错误:<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="utf-8" />&nbsp; &nbsp; <title></title>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; var ua = window.navigator.userAgent;&nbsp; &nbsp; &nbsp; &nbsp; var msie = ua.indexOf("MSIE ");&nbsp; &nbsp; &nbsp; &nbsp; if (!(msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))) //If not IE, load d3 script&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.write('<script src="scripts/d3.js"><\/script>');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; </script></head><body>&nbsp; &nbsp; <svg>&nbsp; &nbsp; &nbsp; &nbsp; <circle class="target" style="fill: #69b3a2" stroke="black" cx=50 cy=50 r=40></circle>&nbsp; &nbsp; </svg>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; if (window.d3) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d3.select(".target").style("stroke-width", 8);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("IE");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript