Member-only story

Does JavaScript load before HTML ?

Pravin M
3 min readOct 13, 2024

--

Does JavaScript load before HTML ?
Does JavaScript load before HTML ?

If you’re on a free Medium plan, click here to read — Free Access

For more questions and answers visit our website at Frontend Interview Questions

The Loading Sequence: HTML vs. JavaScript

When a web browser loads a web page, it processes the HTML document from top to bottom. This means that as the browser encounters HTML tags, it renders the content on the page. However, when it comes to JavaScript, the loading and execution behavior can vary based on how the scripts are included in the HTML.

Default Behavior

By default, when you include JavaScript using the <script> tag in the <head> section of your HTML document, the browser pauses the parsing of HTML to download and execute the script. This can lead to a delay in rendering the page, as the browser must finish loading and executing the script before continuing with the HTML.

Example: Default Script Loading

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Loading Example</title>
<script src="script.js"></script> <!-- JavaScript loads before HTML -->
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>

In the above example, the browser will load script.js before rendering the <h1> element. This means that if script.js contains code that manipulates the DOM (like changing the content of the <h1>), it may not work as expected because the <h1> element has not been created yet.

Improved Loading Strategies

To improve the loading behavior of JavaScript, developers can use various techniques:

  1. Place the <script> Tag at the End of the <body>

By placing the <script> tag just before the closing </body> tag, the browser can load and render the entire HTML before executing the script. This is generally the recommended practice.

Example: Script at the End of the Body

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

--

--

Pravin M
Pravin M

Written by Pravin M

I am a frontend developer with 10+ years of experience Blog :- https://www.frontendinterviewquestions.com

Responses (2)

Write a response