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

82
Visualizações
Variable From Other Script Sometimes not Loading

I have Two JavaScript scripts linked to my HTML File in this order:

<script src="first.js"></script>
<script src="second.js"></script>

first.js has a variable which is accessed by second.js. The Variable is Used by second.js at the end of the file and the variable is defined in first.js at the beginning. Whenever I reload the site, a console error occasionally comes up saying that the Variable in first.js is not defined.

Uncaught ReferenceError: dbis not defined at second.js:80

Why is this? Thanks in Advance.

Full Example:

first.js:

var db = [{name: "Obj1", property: "property1"}, {name: "Obj2", property: "property2"}]; // At Line 8

second.js:

function loadDbItems() {
    for(i = 0; i < db.length; i++) {
        console.log(db[i].name); // Line is Near End of Script
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can register the variable with window to make it global guaranteed.
See script example below.

You should not pollute the window object with every little variable you need, but this way the variable will exist across scripts, provided the first one executes first.

window.db = [{name: "Obj1", property: "property1"}, {name: "Obj2", property: "property2"}];
<html>
  <body onload="loadDbItems()">
    <script>
      function loadDbItems() {
        for(var i = 0; i < window.db.length; i++) {
            console.log(window.db[i].name);
        }
      }
    </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