Reputation: 973
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.
Upvotes: 1
Views: 204
Reputation: 253486
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:
Upvotes: 3
Reputation: 19759
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?
}
Upvotes: 2