I've just learned an important fact about the execution of Javascript in case of an error being thrown. Before I start making conclusions of this I'd better verify whether I am right.
Given an HTML page including 2 scripts:
<script src="script1.js" />
<script src="script2.js" />
script1:
doSomething();
script2:
doSomeOtherThing();
This effectively results in a single script being processed as one unit:
doSomething();
doSomeOtherThing();
In particular, if doSomething
throws an error, the execution is broken. 'script2' is never being executed.
This is my "Lesson 1" - one might think since it is a separately included file it is not affected by script1. But it is. => see "late update" below
Now, if we change script2 as follows (presuming we have jQuery included somewhere above):
$(document).ready({ doSomeOtherThing(); });
and place the script before script2:
<script src="script2.js" />
<script src="script1.js" />
The order of execution is effectively still 'doSomething()' followed (sometime) by 'doSomeOtherThing()'.
However it is executed in two "units":
doSomething
is executed early as part of the document's java scriptdoSomeOtherThing
is executed when the document.ready event is processed.If doSomeOtherThing
throws an exception, it will not break the second processing "unit".
(I refrain from using the term thread
because I reckon that all script is usually executed by the same thread, or more precisely this may depend on the browser.)
So, my Lession 2: Even though a JavaScript error may prevent any subsequent scripts from executing, it does not stop the event loop.
Conclusion 1
$(document).ready()
does a great job in defining chunks of JavaScript code that should be executed independent on any other scripts in succeeding.
Or, in other words: If you have a piece of JavaScript and want to make sure it gets executed even if other scripts fail, place it within a $(document).ready()
.
This would be new to me in that I would only have used the event if the script depends on the document being fully loaded.
Conclusion 2
Taking it a step further it might be a good architecture decision to wrap all scripts within a $(document).ready()
to make sure that all scripts are "queued" for execution. In the second example above, if script2.js
was included after script1.js
as in example 1:
<script src="script1.js" />
<script src="script2.js" />
An error in script1.js would prevent the doSomeOtherThing()
from even being registered, because the $(document).ready()
function would not be executed.
However, if script1.js used $(document).ready()
, too, that would not happen:
$(document).ready(function() { doSomething(); });
$(document).ready(function() { doSomeOtherThing(); });
Both lines would be executed. Then later the event loop would execute doSomething
which would break, but doSomeOtherThing
would not be affected.
One more reason to do so would be that the thread rendering the page can return as soon as possible, and the event loop can be used to trigger the code execution.
Critique / Questions:
Looking forward to any helpful comments!
Late Update:
Like Briguy37 pointed out correctly, my observation must have been wrong in the first place. ("Was I mistaken - yes!"). Taking his simple example I can reproduce that in all major browsers and even in IE8, script2 is executed even if script1 throws an error.
Still @Marcello's great answer helps get some insight in the concepts of execution stacks etc. It just seems that each of the two scripts is executed in a separate execution stack.
JavaScript Errors and generic handling. throw new Error('something went wrong') — will create an instance of an Error in JavaScript and stop the execution of your script, unless you do something with the Error.
Many JavaScript-enhanced web pages have scripts that must be executed automatically when the page is loaded. A web page containing a "scrolling status bar message," for example, should be able to start scrolling the message immediately after the page has loaded, without user interaction.
Whenever the JavaScript engine receives a script file, it first creates a default Execution Context known as the Global Execution Context (GEC) . The GEC is the base/default Execution Context where all JavaScript code that is not inside of a function gets executed. For every JavaScript file, there can only be one GEC.
The way JS handles errors, depends on the way JS is processing the script. It has nothing (or little) to do with threads. Therefor you have to first think about how JS works through your code.
First of all JS will readin every script file/block sequently (at this point your code is just seen as text).
Than JS starts interpreting that textblocks and compiling them into executable code. If an syntax error is found, JS stops compiling and goes on to the next script. In this process JS handles every script blocks/files as separated entity, that's why an syntax errors in script 1 does not necessarily break the execution of script 2. The code will be interpreted and compiled, but not executed at this point, so a throw new Error
command wouldn't break the execution.
After all script files/blocks are compiled, JS goes through the code (starting with the first code file/block in your code) and building up a so called execution stack (function a calls function b calls function d and c....) and executing it in the given order. If at any point a processing error occurs or is thrown programmatically (throw new Error('fail')
) the whole execution of that stack is stopped and JS goes back to the beginning to the beginning of that stack and starts with the execution of the next possible stack.
That said, the reason that your onload function is still executed after an error in script1.js, does not happen because of a new thread or something, it's simply because an event builds up a separate execution stack, JS can jump to, after the error in the previous execution stack happend.
Coming to your questions:
What reasons are there that make it necessary to execute a piece of code immediately, i.e. not wrapping it into the event?
I would advice you to have no "immediatly" called code in your web-application at all. The best practice is to have a single point of entrance in your application that is called inside of an onload event
$(document).ready(function () {App.init()});
This however has nothing to do with error handling or such. Error handling itself should definitely be done inside your code with either conditionals if(typeof myValue !== 'undefined')
or try/catch/finally blocks, where you might expect potential errors. This also gives you the opportunity to try a second way inside of the catch block or gracefully handle the error in finally.
If you can build up your application event driven (not for error handling reasons of course), do so. JS is an event driven language and you can get the most out of it, when writing event driven code...
Would it impact performance significantly?
An event driven approach would IMHO make your application perform even better and make it more solid at the same time. Event driven code can help you to reduce the amount of internal processing logic, you just have to get into it.
Is there another/better way to achieve the same rather than using the document ready event?
As before mentioned: try/catch/finally
Can the execution order of scripts be defined if all scripts just register their code as an event handler? Are the event handlers executed in the order they were registered?
If you register the same event on the same object, the order is preserved.
Your first assumption that they run as one script is incorrect. Script2 will still execute even if Script1 throws an error. For a simple test, implement the following file structure:
-anyFolder
--test.html
--test.js
--test2.js
The contents of test.html:
<html>
<head>
<script type="text/javascript" src="test.js"></script>
<script type="text/javascript" src="test2.js"></script>
</head>
</html>
The contents of test.js:
console.log('test before');
throw('foo');
console.log('test after');
The contents of test2.js:
console.log('test 2');
The output when you open test.html (in the console):
test before test.js:1
Uncaught foo test.js:2
test 2
From this test, you can see that test2.js still runs even though test.js throws an error. However, test.js stops executing after it runs into the error.
I'm not sure about syntax errors, but you can use try {} catch(e) {}
to catch the errors and keep the rest of the code running.
Will NOT run untill the end
var json = '{"name:"John"'; // Notice the missing curly bracket }
// This probably will throw an error, if the string is buggy
var obj = JSON.parse(json);
alert('This will NOT run');
Will run untill the end
var json = '{"name:"John"'; // Notice the missing curly bracket }
// But like this you can catch errors
try {
var obj = JSON.parse(json);
} catch (e) {
// Do or don'
}
alert('This will run');
UPDATE
I just wanted to show how to make sure that the rest of the code gets executed in case the error occurs.
What reasons are there that make it necessary to execute a piece of code immediately, i.e. not wrapping it into the event?
Performance. Every such event fills up the event queue. Not that it will hurt much, but it's just not necessary... Why to do some work later, if it can be done right now? For example - browser detection and stuff.
Would it impact performance significantly?
If you are doing this many times per second, then yes.
Is there another/better way to achieve the same rather than using the document ready event?
Yes. See above example.
Can the execution order of scripts be defined if all scripts just register their code as an event handler? Are the event handlers executed in the order they were registered?
Yes, I'm pretty sure that they are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With