0

I read a bit about where to put the script src in the html-file. Some say at the end of the body, some say in the head. The reason is always a performance issue(because the browser will download first the script and then load the page), not that it will not working anymore at all.

But now i have a very strange behavior:

When i put it in the head or at the beginning, the javascript is not working anymore????? When i put it before the end of the body, everything is fine.

This is my html-code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="doggos.js"></script>
  </head>

  <body>
    <button id="tryIt">Try it</button>

    <p id="demo">huhu</p>
  </body>
</html>

And this is in the doggos.js:

document.getElementById('tryIt').addEventListener('click', function () {
  document.getElementById('demo').innerHTML = 'Hello World';
});

If i put the script-src-phrase at the end of the body my button works and the huhu transforms to Hello World. If i have the script-src-phrase in the head or at the beginning of the body the click on the button does not change anything (the JavaScript seems to be not available).

I am a bit confused, because these are very "simple codes" and i don't know where my fault is with the solution to put it in the head, like often recommended.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Sun23
  • 77
  • 8
  • 2
    Because the HTML elements do not exist when the script is run – evolutionxbox Nov 23 '21 at 18:49
  • It's possible your script is running before the DOM has rendered your elements. See [$(document).ready equivalent without jQuery](https://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery). – D M Nov 23 '21 at 18:50
  • 2
    A little hack just add defer tag in script :-) – Sanmeet Nov 23 '21 at 18:50
  • 1
    @Sanmeet that’s not a hack, but a perfectly good solution – evolutionxbox Nov 23 '21 at 18:50
  • @evolutionxbox I called it a hack since for me it seems like a trick ... I know how defer tag makes the script load after document is loaded.... – Sanmeet Nov 23 '21 at 18:53
  • Thanks for the help :) The defer-"hack" was the solution. And especially thanks to the person, who showed me the other question, where is a big explanation for a lot of these problems :) – Sun23 Nov 24 '21 at 17:16

0 Answers0