JavaScript code in a browser is executed in a single thread
No two event handlers will ever run at the same time
Document contents are never updated by two threads simultaneously
No worries about locks, deadlock, or critical region
But web browser “stops” responding to user input while script is running
JavaScript Execution Timeline in Browser
document object is created and document.readyState is set to loading
Browser downloads and parses the page. Scripts are downloaded and executed synchronously in the order they appear in the page (if no async)
async script starts to be downloaded asynchronously in the background and gets executed as soon as they are available
Once the page is completely parsed, document.readyState is set to interactive
Browser fires DOMContentLoaded event and calls document.onload callback
document.readyState is set to complete
Browser waits for events and calls appropriate event handlers
Execution Timeline Example
<html>
<head><title>JavaScript Example</title></head><body>Click on this document!</body><script>let colors = [ "yellow", "blue", "red" ];
let i=0;
functionChangeColor(event) {
document.body.style.backgroundColor = colors[i++%3];
}
document.body.addEventListener("click", ChangeColor);
</script>
</html>
Q: What will happen if we move the <script>...</script> before <body>...</body>?
Notes on JavaScript Execution
HTML DOM object manipulation can be done only after the object has been parsed and loaded, not before
To run initialization code, set the onload handler with the initialization code
To run final cleanup code, set the onunload handler
window: Global Object (1)
window object is the “global object” within a browser
All global variables and functions become properties and methods of window
e.g., document is in fact window.document
window.location: the URL of the current page
By setting this property, we can load a different page
window.history: browsing history
window.history.back(), window.history.forward()
window: Global Object (2)
window.alert(), confirm(), prompt(): open a dialog box
alert("hello, world!"); // returns nothing
response = confirm("Click OK to proceed, Cancel to return");
// returns boolean
name = prompt("Type your name"); // returns string