HTML5 SVG Support check using JavaScript – the simple way

My last post talked about how you can detect whether your browser supports HTML5 Canvas or not using simple JavaScript technique. Based on the same principles, this post illustrates how you can detect if your browser supports SVG elements. You may note SVG is Scalable Vector Graphics and HTML5 has native support for SVG tags. The difference with Canvas is that in case of SVG elements, they become a part of the DOM and you can manipulate each SVG elements, whereas in case of Canvas, the entire <canvas></canvas> tag becomes one node in the DOM and anything inside the Canvas <canvas> tag (for eg. a Rectangle) cannot be manipulated individually using standard DOM methods. Browse the web and you will find a hell lot of topics on this.

Alright, now back to the detection code. Just copy/paste this inside your window load / body load or in case of JQuery the $(document).ready() method,

if(!document.createElement('svg').getAttributeNS){
  document.write('Your browser does not support SVG!');
  return;
}

So, if your browser does not support SVG, then it will not process further (in case your application cannot live without SVG). But if you have a back up plan and you can live without SVG in your browser, then you can add an else block along with the if so that you can write your backup logic.

Explanation
Well, the code is very simple. Inside the if condition I create a SVG element using the standard DOM createElement() method. Now this will create a <svg></svg> object. Now next thing I do is to check if the getAttributeNS() method is defined or not. If you browser does not support <svg> then there is no way it will understand getAttributeNS() and that’s the catch.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s