network optimization :

load javascript asynchronously

1). When you place the javascript inside the head tag: execute the HTML until it reaches the js script tag, it reaches then it will stop the execution of HTML and make a request and get the javascript file from the server and then execute that javascript after that it will continue the HTML execution (parsing).

the main drawback is blocking the HTML execution(parsing). it will stop dom tree construction

<html lang="en">
	<head>
		<title>Document</title>
		<script src="./js/script.js"></script>
	</head>
	<body>
		<h1>hello</h1>
	</body>
</html>

async: if you place the script tag inside the head with the async attribute, it will execute the HTML until downloading the javascript, after completion downloading then it will stop the HTML execution(parsing). execute the javascript then only continue the html execution (parsing).

defer: defer attribute tells, hey you can start the parsing, the moment you come to a script tag then you download it and continue the parsing. basically, it will fetch the javascript from the network and it will keep it somewhere for you, the moment the browser finishes parsing. now our javascript will be executed.

it is the more optimal approach because prefetch the javascript code during parsing.

pre-fetching helps us to improve the performance

when javascript is placed after the body.

first, it will execute the HTML and then after completing html body, it will reach to script tag then the browser make a request and get the javascript and execute it.

it is more optimized than being adding it in the head tag.

example :

<html lang="en">
	<head>
		<title>Document</title>
	</head>
	<body>
		<h1>hello</h1>
	</body>
	<script *src*="./js/script.js"></script>
</html>

where do we place a script tag in the HTML and why?

adding a script tag with differ attributes and pre-fetching concepts and all but you have to start with

or usually, we place the script tag after the body at the very end of the HTML code so that when the parsing is completed we can download the javascript and execute it, but we can do much better this. by using differ attributes of the script tag.