Which SVG support detection method is best?

spraff picture spraff · Mar 13, 2012 · Viewed 8.9k times · Source

Somebody has already asked my question about detecting SVG support in browsers but there are three leading solutions and not a lot of discussion about the merits of each.

So: which, if any, is best? In terms of portability and correctness, that is. False negatives (i.e. "no svg") are undesirable, but acceptable; false positives are not.

Exhibit A:

var testImg = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D';

var img = document.createElement('img')

img.setAttribute('src',testImg);

return img.complete; 

Exhibit B:

return document.implementation.hasFeature(
    "http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");

Exhibit C:

return !! document.createElementNS &&
       !! document.createElementNS (
             'http://www.w3.org/2000/svg',
             "svg")
      .createSVGRect;

Answer

James Donnelly picture James Donnelly · Jan 30, 2015

No need to include the entire Modernizr library for this. Here's a simple check that I've used in the past:

typeof SVGRect !== "undefined"; // true if supported, false if not

This quite simply checks for support of the SVGRect object which is defined in the SVG Specification. In Chrome, typeof SVGRect is "function" and in IE9 it's "object", but in browsers which do not support SVG (IE8, for instance) this returns "undefined".

With the above code, you can simply:

if (typeof SVGRect !== "undefined") { ... /* If the browser does support SVG. */ }
else { ... /* If the browser does not support SVG. */ }