Following html file through javascript errors when loading.
index,html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
script.js
document.body.innerHTML="<h1>Hello world </h1>
If you look at the javascript console you can see
The javascript is executing before the document is loaded. We can differ the execution of javascipt file loading using difer attribute in script tag. If this tag is present the script will execute after the page is finished parsing.
<script src="script.js" defer></script>
In this case the javascript will load only after the document is loaded.
The attribute async will move the execution of script asynchronously with the rest of the page.
<script src="script.js" async></script>
You can put the script tag after the body as well.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script src="script.js"></script>
</html>