0

When one should use the javascript in head section in html. And if I print my name in the head section using javascript something like this :-

<!DOCTYPE html>
<html>
<head>
<script>

document.write('akshat');

</script>
</head>
<body>

<h2>Demo JavaScript in Head</h2>


</body>
</html>

then where it is going to print my name which I print with the help of javascript code? before body elements or after?

  • 3
    Does this answer your question? [What's the difference between putting script in head and body?](https://stackoverflow.com/questions/17106462/whats-the-difference-between-putting-script-in-head-and-body) – D-Money Sep 23 '21 at 15:43
  • 1
    _"then where it is going to print my name which I print with the help of javascript code? before body elements or after?"_ Why don't you just try it out? You should also read [Why is document.write considered a "bad practice"?](https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – Thomas Sablik Sep 23 '21 at 15:45
  • 1
    1) Your code has a syntax error: remove that `}`. 2) Your name will be printed before the markup. 3) You can easily test this yourself by creating an html file and opening it in the browser. – Andy Sep 23 '21 at 15:45
  • The main reason to not put the script in the head, is to make sure the elements it is accessing are already rendered. I personally put normal sized script in the head and use load event handler – mplungjan Sep 23 '21 at 15:52

0 Answers0