I try to simulate a problem where a script that is loaded from an external url stops execution of any more scripts on my site.
I tried to simulate such a problem by calling a function that does not exits. I can see the error in firebug but different scripts on the page are still executed.
Are there different kinds of errors in Javascripts? If yes: what kind of error stops script execution? I only need this answer for Firefox.
EDIT
This question is easy to misunderstood but Rob W got it: I need to throw an exception and that exception needs to stop further script execution.
Different
<script>blocks are executed separately. You cannot prevent the second block from execution by throwing an error in the first block (Demo: http://jsfiddle.net/WJCEN/).Also, if an error is caught using
try-catch(demo: http://jsfiddle.net/WJCEN/1/), then the error will not even stop the execution a whole block.There is no general one-fit-all method to stop all code from running. For individual scripts, you can use some tricks to prevent the code from running further.
Example 1 (demo): Temporary overwrite a method
This method is based on the fact that script 2 expects
alertto be a function. We have rewrittenalertto a non-function property (script 1). Script 2 throws aTypeError, and the second block is skipped.We restore the original values in script 3.
Example 2 (demo): Define a constant method, which cannot be overwritten.
This methods relies on the
Object.definePropertymethod, to effectively define a constant value. In strict mode, thevar testdeclaration would throw a TypeError: “test is read-only”.When strict mode is not enables, a TypeError will be thrown at
test(): “test is not a function” (because we definedtestto be constant, in script 4).Note: The last method is not working correctly with function declarations (see bug #115452, Chrome 17)