Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!