Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
Why my code doesn't work when the script tag is in the head tag?

I was making a webpage with a video. and I wanted to change the size of the video depending on the size of the window.

the code below is my HTML code:

<video id="video" controls="controls" poster="images/video_poster.png" width="320" height="240">
      <source src="video/Minions.mp4" type="video/mp4">
      <source src="video/Minions.ogv" type="video/ogg">
</video>

and my script code for that is below:

  <script>var video = document.getElementById("video");
    function changeVideoSize() {
      console.log("width is: ", window.innerWidth)
      if (window.innerWidth > 900) {
        video.width = "640";
        video.height = "480";
      }
      else {
        video.width = "320";
        video.height = "240";
      }
    }
    window.addEventListener("resize", changeVideoSize)
    function init() {
    }
    init();
  </script>

first, I place this script code at the end of the head tag, and it made an error "Cannot set properties of null (setting 'width')".

I was stuck with this error for an hour... and then after many different tries, I put it at the end of body tag, and it worked.

Why is it? What are the main differences between putting it in head and body?? Should I always put the script tag at the end of the body tag? or it depends on the cases?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

That is because of the pure sequence. The interpreter reads from top to bottom in this case. and if your code in the head says get me element X and it is not yet in the DOM, then that is null. It's different in the footer, where element x is already loaded in the DOM, and that's why the script works. JS in most cases always just before the closing body tag.

about 4 years ago · Juan Pablo Isaza Relatório

0

basically when you are putting it in your head tag , then script is parsing before body tag. so there is no video tag inside document with id video. Use external script with defer attribute or put script below your html code inside the tag. Sorry for my bad english.

about 4 years ago · Juan Pablo Isaza Relatório

0

First, the HTML get parsed from top to bottom, So Whatever encounter first will get run.

If you put script tag at the end of the head tag then It will run first before the HTML body so you can't set width because when you used

document.getElementById("video")

It would return null so you can't set properties on null. Because at the time of this statement the element doesn't exist.

<html>

<head>
  <script>
    const heading = document.querySelector("h1");
    console.log(heading); // null
  </script>
</head>

<body>
  <h1> This is heading</h1>
</body>

</html>

So you have to put the script tag at the end of the body tag. So that the when JS get parsed and gets executed then It can find the HTML element and executes the statements.

<html>

<head>
</head>

<body>
  <h1> This is heading</h1>
  
    <script>
    const heading = document.querySelector("h1");
    console.log(heading); // h1 element
  </script>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda