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

233
Visualizações
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 Respostas
Responde à pergunta

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