Could anybody suggest how can I test if a particular line of JavaScript code is supported by Browser or not. If not how can I handle it? As I am learning JavaScript it would be a great help to know.
2 Answers
This would seem to be the perfect time to use try/catch:
try {
// your JavaScript here
document.executeSomeUnknownFunction();
}
catch (error) {
console.log("There was an error: " + error);
}
console.log("...but nothing broke");
Or, alternatively, assuming it's a method of an Object you're testing for (for example querySelectorAll()):
if ('querySelectorAll' in document) {
console.log("We support 'document.querySelectorAll()'");
}
References:
6 Comments
Thilo
Might be that something does not work, but there is no exception.
David Thomas
True, but it depends what 'that' might be; and given the limited information in the question it's hard to account for possibilities I can't anticipate.
Thilo
That's right. This question can most likely not be answered in a general way. Like @jfriend00 said in the comments: The techniques vary depending upon what it is.
Thilo
BTW: console.log might also not supported ;-)
David Thomas
@Thilo: that would be entertainingly ironic... :D
|
You can either: 1) Assume that the code works, and handle the cases where it doesn't:
try{
// ...
}catch(e){
// an error occurred
}
Or 2) check if the function it relies on exists, and then use it:
if(window.yourfunction){
// The function is present in the global scope
}else{
// Not available, try alternatives?
}
windowobject for existence of the API you wanti++ornew Map()? Or do you want to conditionally execute code in your own module?