This is my model for how a Javascript program runs.
browser load document - this is a stream of data with a type specified by the http protocol. The initial data is loaded. For Javascript, this is some form of HTML document.
html parse - The loaded HTML defines the environment for our program. There is the
document
object and thewindow
object. Our code is loaded into the window object by<script>
tags, and the first immediately-executable lines of Javascript can access anything that has been defined before it. Knowing the order of definition and load is critical. In general, Javascript user interface code references thedocument
object and stores its data/functions in thewindow
object. Note that the global object iswindow
; you don't need to prefix objects withwindow
to access them.DOM instantiated - Each parseable tag is interpreted on-the-fly in the order its defined in the HTML file, though the objects they define may not created right away. This depends on the specific tag. Ideally we defer the initialization of our Javascript code explicitly when the
loaded
event fires by hooking into it withdocument.addEventListener()
At this point, the DOM and initial Javascript code is loaded. We can further modify the code on specific events; combined we can create dynamically-loaded code elements
- event hooks can be defined in the tags themselves or by javascript to be sent to an event handler which can execute other Javascript.
- additional scripts can be loaded by instantiating a
<script>
element and appending it to thedocument
, which will make it load. - element modification of DOM objects is how we make an interactive interface.
- messages can be sent between the document itself and web workers
- websockets can fire events on data received, or return new data on request.