To answer as tersely as possible, here's what happens:
- You request a page.
- The server sends you a response containing HTML.
- The browser looks for external resources (
<script>
, <link>
, etc.) and starts downloading those.
- When it encounters a
<script>
block, it immediately executes the code contained either within the tag or in the downloaded Javascript file.
This all happens inside the browser; the server only knows about which files were sent down the line to the browser. No other information (including how and if the Javascript code executed in the browser) is available to the server unless specifically transmitted to the server in the form of new requests.
As for Javascript, it's a dynamic language and most browsers handle it using execution within virtual machines that understand bytecode that the interpreter generates when reading the source code. The virtual machine itself then executes the bytecode on the hardware in the appropriate instruction set.
In the case of executing Javascript on a page, the global context is what is passed to the execution engine, so any changes made by the executing Javascript will affect that context; in the case of browsers and web pages, that is the window
object.