spr*_*aff 18 javascript svg browser-feature-detection
有人已经问过我关于在浏览器中检测SVG支持的问题,但有三个主要的解决方案,而不是很多关于每个优点的讨论.
那么:哪个,哪个最好?在便携性和正确性方面,即.假阴性(即"没有svg")是不受欢迎的,但是可接受的; 误报不是.
图表A:
var testImg = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D';
var img = document.createElement('img')
img.setAttribute('src',testImg);
return img.complete;
Run Code Online (Sandbox Code Playgroud)
图表B:
return document.implementation.hasFeature(
"http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");
Run Code Online (Sandbox Code Playgroud)
图表C:
return !! document.createElementNS &&
!! document.createElementNS (
'http://www.w3.org/2000/svg',
"svg")
.createSVGRect;
Run Code Online (Sandbox Code Playgroud)
Jam*_*lly 38
无需为此包含整个Modernizr库.这是我过去使用过的简单检查:
typeof SVGRect !== "undefined"; // true if supported, false if not
Run Code Online (Sandbox Code Playgroud)
这非常简单地检查SVG规范中SVGRect定义的对象的支持.在Chrome中是IE9 ,但是在不支持SVG(例如IE8)的浏览器中,这会返回.typeof SVGRect"function""object""undefined"
使用上面的代码,您可以简单地:
if (typeof SVGRect !== "undefined") { ... /* If the browser does support SVG. */ }
else { ... /* If the browser does not support SVG. */ }
Run Code Online (Sandbox Code Playgroud)