Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
Include a JS file directly in another?

Let's say I have two JS files, which are both obviously representative of larger files. The first is root/foo.js:

let foo = true;

The next is root/foopolice.js. This code depends on root/foo.js, and by itself, it throws an error:

function patrol(){
  if (foo) alert("Found foo"); // ReferenceError

Finally, there is root/index.html, which links the two:

<script src="/foo.js"></script>
<script src="/foopolice.js"></script>
<button onclick="patrol()">Patrol for foo</button>

The question is, how would I "include" the variable defined in root/foo.js directly into root/foopolice.js without combining the two into one? The use of both script tags is not enough, because root/foopolice.js would still warn of a nonexistent error while I edit it. I'm open to solutions using JQuery or just vanilla JS, depending on best practice.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Typically, a build process is used to create a JS bundle that would extract and combine all of the required code from multiple files (see Parcel or ESBuild).

Without a build process, modern JS modules (also known as "ES modules") could be imported using <script type="module">. JQuery can be avoided entirely in 2020 and beyond.

library.js

const name = 'Jane Doe'

export {
  name
}

main.js

import { name } from './library.js'

function sayHello() {
  console.log(`hello ${name}!`)
}

window.addEventListener('DOMContentLoaded', event => {
  document.querySelector('button').addEventListener('click', sayHello)
})

index.html

<script type="module" src="main.js"></script>

<button>Say Hello</button>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda