JavaScript Browser Compatibility Issues
Working on a web project and running into the usual browser compatibility headaches. IE is being particularly troublesome, as always.
The Problem
Code that works perfectly in Firefox and Chrome breaks in Internet Explorer. Getting tired of writing browser-specific workarounds.
Common Issues I've Hit
1. Console Object
IE doesn't have console.log unless developer tools are open:
// Safe logging
if (window.console && console.log) {
console.log("Debug message");
}
// Or create a stub
window.console = window.console || { log: function() {} };
2. Array indexOf
IE8 and below don't have Array.prototype.indexOf:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(item) {
for (var i = 0; i < this.length; i++) {
if (this[i] === item) return i;
}
return -1;
};
}
3. JSON Object
IE7 and below don't have native JSON:
// Include json2.js or check for it
if (!window.JSON) {
// Load JSON library
document.write('<script src="json2.js"><\/script>');
}
4. Event Handling
Different event models between browsers:
function addEvent(element, event, handler) {
if (element.addEventListener) {
element.addEventListener(event, handler, false);
} else if (element.attachEvent) {
element.attachEvent('on' + event, handler);
}
}
5. XHR Creation
IE uses different object:
function createXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
My Testing Strategy
- Primary development in Firefox (best debugging tools)
- Regular testing in Chrome and Safari
- IE testing on actual Windows machines (VirtualBox)
- Mobile testing when possible
Tools That Help
- jQuery - abstracts away most compatibility issues
- Modernizr - feature detection instead of browser detection
- HTML5 Shiv - for IE HTML5 support
- json2.js - JSON support for older browsers
Browser Market Share (2012)
Based on what I'm seeing:
- IE still has significant market share (unfortunately)
- Chrome is growing fast
- Firefox is solid
- Mobile browsers becoming important
Conclusion
Browser compatibility is a pain but necessary. The key is having a good testing process and using libraries that handle the heavy lifting.
Looking forward to the day when we can drop IE8 support!