Best way to prevent Javascript from failing.

Javascript is a great flexible language but has a major flaw with portability. I call it the “1 Hit Combo super punchy epic fail” error, aka Error Object. The Error object has 6 beautiful children that everyone hates to see. Their names are EvalError, RangeError, ReferenceError, SyntaxError, TypeError and URIError, and your task a good professional Frontend programmer is to prevent those 7 object from never stepping foot onto your website. So here are some simple tips to assist you in your struggle.


Solution 1:
First off, you should check your code to make sure that you’re not the one causing the errors message.
So check your code with code analysis tools like JSlint, console2 (a firefox addon ) or Google’s Closure inspector.

Solution 2:
If possible you could also wrap your error prone code in try or catch blocks.
Try and Catch works as follow.

Sends an error message to the browser and further Javascript from executing.

1
2
var obj = [];
obj[0] = globalVar;    //ERROR!

Send the error message to the catch block and let’s the developer decide what to do.

1
2
3
4
5
6
7
try{
    var obj = [];
    obj[0] = globalVar;
}
catch( err ){
    alert( "Error Message: " + err.message ); //You should log the error instead of alert it.
}

Solution 3:
For a page that requires javascript, you can load that page with a iframe. With a iframe or frame, even if your main page halts due to an error, your javascript in your iframe will continue to run.

1
2
3
<iframe src="javascript_page.html" width="100%" height="30">
  <p>Your browser does not support iframes.</p>
</iframe>

For something else that might help, check out ADSAFE (protection against 3rd party scripts).

References:
MDN Doc Center: Error
Stackoverflow : Is it possible to “sandbox” arbitrary JavaScript to only operate on one div and not the whole document?

(Page view Count: 40)