1

Often times when I'm writing my JavaScript code I can't shake the paranoia that some function or line of code is going to break in this browser or that...

How can I check to see if the code I'm writing is x-browser compatible?

2
  • 1
    Are you talking about language feature, or DOM API compatibility? Can you give any specific example? Commented Jan 4, 2011 at 20:18
  • I think this question is too simplistic and broad to answer adequately. You asked about language features, that would mean new stuff in the actual language like const, getters, and the like. But I think you mean DOM and BOM features, like document.activeElement, which people have given you a few clues. But there isn't one answer for all your needs. The basic idea is feature detection (ejohn.org/blog/future-proofing-javascript-libraries) over browser detection. However, this won't tell you about bugs in features, only that they are implemented. Commented Jan 4, 2011 at 20:40

3 Answers 3

4

Basic feature detection can be done by querying window properties, eg window.XMLHttpRequest.

In certain cases it becomes a lot more complex than just querying properties, since methods defined can be inconsistent with one another. In that case it really depends on the scenario but certain times you may need to do something as dirty as creating an element that's offset from the screen, then set certain properties and see if those changes reflected or not.

It would probably be useful if you specifically gave examples of certain cases, as there are literally thousands of things to feature detect for and not everything is the same.

Sign up to request clarification or add additional context in comments.

Comments

0

You can check if the function for the feature you want to use exists like this:

if(functionOrObjectName) {
    //will execute if the function or object is defined
}

1 Comment

This will thrown an error if a variable or function is not defined. typeof undefinedVar will return 'undefined' for undefined vars and functions. What you suggest does work if you are testing for a property. So to test for global functions and vars (which are props of the window object) you can use if (window.undefinedVar) which will not cause an error
0

You might find this test/compatibility table site handy: http://robertnyman.com/javascript/ .

Check out has.js too. It should simplify feature detection a bit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.