JavaScript Essentials: Compatibility

JavaScript Essentials: Compatibility

Example

For simplicity’s sake, I’m going to call a function called “doesntWorkInIE6()” which doesn’t work in Internet Explorer 6. For this example, all that function is going to do is return the string “Hello there.”

	<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Hello there</title>
	<script language="javascript" src="doesntworkinie6.js" type="text/javascript"></script>
	</head>
	<body>
	<script>
	(function() {
	alert(doesntWorkInIE6());
	})();
	</script>
	</body>
	</html>
	

Sometimes you can’t trust functions we didn’t write to work all the time. In this case, we will not have access to doesntworkinie6.js, but we can control how we execute it’s internal functions. Through our extensive testing, we find out that it doesn’t work in IE6 and there’s no way around it. So we’re going to simply check if it’s IE6, and if it is, we will not run the function.

	<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>Hello there</title>
	<script language="javascript" src="doesntworkinie6.js" type="text/javascript"></script>
	</head>
	<body>
	<script>
	function thisIsIE6() {
		return 'Hello IE6';
	}
	(function() {
		var ua = navigator.userAgent;
		var ieo = ua.indexOf('MSIE ');
		if (ua.indexOf('MSIE ') != -1) {
			parseFloat(ua.substring(ieo+5, ua.indexOf(';', ieo))) < 7 ? alert(thisIsIE6()) : alert(doesntWorkInIE6());
		}
		else {
			alert(doesntWorkInIE6());
		}
	})();
	</script>
	</body>
	</html>
	

Here we check if it’s an Internet Explorer browser, then we check if it’s IE6. Thare are definitely other ways to do this, but I just want to get the point across that sometime’s it is necessary to do this–semantically it’s up to you how you do it.

Review

That’s it for this week. It’s a pretty broad subject, so I challenge anyone to bring up any topics for next week’s session and provide examples of situations where compatibility is an issue. There isn’t always a single solution which will fit all situations, so it’s good to explore options. Sometimes you only have to create compatibility code for 2 groups, sometimes 3 groups, sometimes more. Remember to keep an analytical mindset and try not to let browser-specific issues throw you off too much!

No one said web development was easy :)

About the Author

Designer, developer, and excellent napper.