1. Computing

JavaScript By Example

24. Feature Sensing

From , former About.com Guide

Not all browsers support exactly the same version of JavaScript. Internet Explorer further complicates things by supporting a slightly different language called JScript which has most but not all JavaScript as a subset. This means that particular JavaScript statements may not always work across all browsers. In most of these cases there is either an alternative provided or we can add our own or even just not run the JavaScript in those browsers.

To be able to handle these differences we need to be able to select and run the code that the particular browser supports but that does NOT mean we need to work out which browser it is (which in any case isn't possible). JavaScript has always supported feature sensing which means that we can first test if a function, method, or object is supported before we try to run the code that relies on it..

In this example we have created a function that determines whether or not the browser supports Ajax and the code does feature sensing for a couple of the different ways that the browser might use to supply that support.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example 24</title>
</head>
<body>
<p>Ajax is <b id="script">not </b>supported.</p>
<script type="text/javascript" src="example24.js"></script>
</body>
</html>

JavaScript


function supportsAjax() {
var avers;
if (typeof XMLHttpRequest != 'undefined') return true;
else if (window.ActiveXObject) {
avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp"];
for (var i = avers.length -1; i >= 0; i--) {
try {
httpObj = new ActiveXObject(avers[i]);
return true;
} catch(e) {}
}
}
else return false;
}
if (supportsAjax())
document.getElementById('script').style.display = 'none';

©2013 About.com. All rights reserved.