HTML5 Tutorial: checking for browser support

Checking for browsersupport.

Checking browser support

At the time of writing this article, (some of) the HTML5 and CSS3 specifications are still drafts. Different browsers have different paces in the adoption of several new HTML5 and CSS3 features.

On http://caniuse.com/ you can find detailed information about browser support for all kinds of CSS3 and HTML5 features, neatly summarized in clear tables

browser support
On http://caniuse.com/ you will find detailed information about browser support for all kinds of CSS3 and HTML5 features.

Detecting Browser support

If you want to use HTML5 features in your web page, it is necessary to check for browser support so that alternative content (also known as fallback content) may be offered to non-supporting browsers. This principle is also known as graceful degration. For detecting browser support for a particular feature, you can use 'Modernizr', a javascript library for detecting browser features. Modernizr makes use of so-called object-detection.

Modernizr
You can create your own custom Modernizr file with a selection of the browser objects you want to check for!

In the example below Modernizr checks whether or not there is support for the Canvas object in your browser. When Modernizr.canvas returns true then the canvas element will be loaded, otherwise a fallback div, containing a message such as "Your browser doesn't support Canvas. Please update your browser." will be loaded.

Canvas detection using Modernizr

<!doctype html>
<html>
<head>
<title>Canvasdetection using Modernizr </title>
<script src="js/modernizr.js"></script>
<script>

function detect(){
	if (Modernizr.canvas) {
	// canvas is supported. Do your Canvas thing.
	CanvasSupported();
	}else{
	//canvas is not supported. Use fallback content.
	CanvasNotSupported();
	}
}

function CanvasSupported(){
  var canvas = document.getElementById("SupportedCanvas");
  var alternative = document.getElementById("NonSupportedCanvas");
  var context = canvas.getContext("2d");
  var x = 20;
  var y = 20;
  context.font = "20pt Trebuchet";
  context.fillText("Congrats! Your browser supports Canvas", x, y);
  alternative.style.display = 'none'; 
};

function CanvasNotSupported(){
  var canvas = document.getElementById("SupportedCanvas");
  var alternative = document.getElementById("NonSupportedCanvas");		
  canvas.style.display = 'none'; 
};
  window.addEventListener("load", detect, true);
</script>
</head>
<body>
  <canvas id="SupportedCanvas" style="border: 1px solid;" width="636" height="288"></canvas>
  <div id="NonSupportedCanvas" class="defaultBlogIntroImage"><span>Your browser doesn't support Canvas</span></div>
</body>
</html>

Below you can see the result of this script in your browser.

Your browser doesn't support Canvas

Leave a comment