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

219
Vistas
How do I pass a variable to a script as it's being loaded?

I'm adding a script to my page:

<script src="https://example.com/script.js"/>

But I would like to be able to pass a "key" to this script as it's being loaded, the key needs to be accessible by the loaded script, as it depends on it.

How can I do this?

Ideally something like this would be great:

<script src="https://example.com/script.js?key=authkey"/>

But I can't find much on getting this to work.

So far I've been adding an extra meta tag:

<meta
  name="key"
  content={"authkey"}
/>

And accessing it from the script:

const key = document.getElementsByName("key")[0].content;

But this isn't great. I also found this answer but it's not much better.

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

0

You can create new Element script pass its src as your shown link and append in body

window.addEventListener("load", () => {
  const script = document.createElement("script")
  script.src = "https://example.com/script.js"
  document.body.appendChild(script)
  
  const meta = document.createElement("meta")
  meta.name = "key"
  meta.content = "authkey"
  
  document.getElementsByTagName('head')[0].appendChild(meta)
  
  const key = document.getElementsByTagName("meta")[0]
  console.log(key.name)
})

Edited: I couldn't add key property as attribute if I wouldn't use setAttribute("key", "key"), I used that method but appeared another problem

when I was grabbing that meta tag from document.head, it was showing that added Element, I also could print its content but not key, maybe because meta tag's default attribute isn't key, attributes that you can pass there are only charset, content, http-equiv and name, when I was printing key.name it was returning "undefined", and then I changed key to name and worked perfectly, if attribute name doesn't cause problem for you everything works well

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