Javascript browser compatibility

As you have started to see there are a range of problems with JavaScript caused by the fact that not all browsers use the official DOM to describe Web pages. There are some examples at the bottom of this page but first how to handle those problems.

Knowing everything v. experimenting

One option is to know all of the problems caused by all of the browsers. That's not impossible as there are a number of sites out there which list many of them. It's still a lot to learn though.

The other is to learn proper (official) JavaScript and always use that. Then test the pages in all the major browsers to see if it works. If it works in most browsers but not others then you can search the Web for the cause and possible cures.

What to do once you know the problem

Most of the problems will be like the one you saw on the pages about innerHTML, innerText and textContent or keyCode and which. IE uses one method and most other browsers use another.

On those pages you saw two ways to achieve the same thing. Some people will try to find out which browser is being used and then use appropriate code. The problem then is how to deal with new browsers and browsers can also lie about what they are. What you need to do is find out which method will work on the current browser:

if (document.getElementById('fred').textContent) {
    document.getElementById('fred').textContent='This element is called fred';    
} else {
    document.getElementById('fred').innerText='This element is called fred';                        
}
        

The IF statement checks to see if the browser knows what textContent is. If it does then that object will be used to set the text content. If not the value of textContent will be null and the alternate method will be used.

The general principle is to check for the presence of the DOM object you want to use and then use it if it is there.

Common incompatibilities (if they are links click to see sample code):

Testing your scripts in older browsers

You can see your pages in versions of Internet Explorer from 5.5 to 8 using IETester.

If you want to see what really old browsers could do then try dejavu which can emulate the earliest.

submit to reddit Delicious Tweet