When script
elements do not use the async
or defer
attributes, the browser will execute JavaScript code as it encounters it while parsing the document. If there are multiple script elements, they will be executed in the order they appear.
Even code that is wrapped inside a function may be executed immediately without any specific event triggering it if the function is directly called. For example:
<script>
function test() {
alert("Test");
}
test();
</script>
The browser's behavior of executing script elements in order is crucial because if a script element in the middle of the document performs tasks like document.write()
, the output will be displayed where the script element is located. Additionally, if the script attempts to manipulate elements in the document, it only has access to elements above it since those below have not yet been parsed. Furthermore, JavaScript within a script can access global functions and variables declared in earlier script elements.
"I feel like it would probably be one of the window/document onload events"
Contrary to the assumption, functions explicitly bound to the window/document onload events will be executed only when triggered. Other code snippets, as shown in the question and above, will run prior to the onload event.
The async
and defer
attributes introduce changes, mainly on browsers that support them. These attributes pertain to script
tags that reference external JavaScript resources, for example:
<script async src="my.js"></script>
A comprehensive discussion on these attributes goes beyond the scope of this response, however:
- Using either
async
or defer
allows the HTML parser to continue building the page without waiting for JavaScript code execution
- Scripts with
async
may be executed out of order, running as soon as they are available
- Scripts with
defer
will be executed in sequence after the parser completes building the page
- Combining
async
and defer
on the same script
tag results in async
taking precedence