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

184
Visualizações
Running order of multiple scripts in an HTML document?

I have an HTML page that i ship to the browser and it contains a couple of script tag.

This is my index.html file:

  <body>
    <div id="app"></div>

    <script src="src/index.js"></script>

    <script>
      window.test = true;
    </script>
  </body>
</html>

And this is my src/index.js file:

<script>

const test = () => {
  if (window.test) {
    console.log("wow!");
  }
};

test();
</script>

In the HTML file, i define window.test after i run the src/index.js. src/index.js will only print to the console if window.test is set to true, but that's being set only after, as the second script.

What is the order in which these scripts will run? Is there a guarantee that window.test will always be set to true "just in time" for the if statement in src/index.js to print wow!?

CodeSandbox: https://codesandbox.io/s/javascript-forked-utgh8?file=/index.html

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

0

In JS called from HTML file the order of the scripts are just like their order of writing in this file "always" will be in that order, which means that in your example window.test Will always have a null value in index.js so nothing will be printed in the console

about 4 years ago · Juan Pablo Isaza Relatório

0

to guarantee that test function is only call after variable is setted why not use a custom event

<script src="src/index.js"></script>

<script>
  window.test = true;
  const event = new Event('test-setted');
  document.dispatchEvent(event);

</script>

and in index.js

<script>

const test = () => {
  if (window.test) {
    console.log("wow!");
  }
};
document.addEventListener('test-setted', function (e) { 
    test(); 
}, false);

</script>
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