Reputation: 1631
After read how browser works and browser rendering process, I still have confusion about browser parse process when encounter <script>
tag, which the posts not really cover.
The main process is described in the following pic:
Suppose we have a simple html
<html>
<head>
<link rel="stylesheet" href="main.css">
<script src="main.js"></script>
<link rel="stylesheet" href="another.css">
</head>
<body>
</body>
</html>
Questions:
<script>
tag, does browser halt until js file is downloaded and executed complete? For this example, browser will not download another.css
until main.js
download and execute?Upvotes: 5
Views: 1443
Reputation: 71
1: The browser is not singlethreaded, if you keep an eye on your taskmanager, you'll see that the browser in fact uses several threads. i think the browser reserves 1 thread for the htmlpage, and creates a new thread/reuses threads to fetch images, css and js, thus not blocking the main html-thread.
2: When the HTML parser encounters the <script src="main.js"></script>
tag, it will download the main.js to the client and execute whatever js-code it can find.
Normally it would be in your best interests to halt the execution of the js. This is why you normally put all your js functionality into functions and have an init or load function that triggers your js when all elements on htmlpage are loaded.
You can do this by attaching an eventlistener to the body.onload-event
<body onload="load()">
where load() is a function in your main.js
Take a look at this: Link
Upvotes: 7