Home > Net >  How to Use JavaScript Variable in HTML src tag
How to Use JavaScript Variable in HTML src tag

Time:12-17

I have a src tag in my HTML which includes a private API key. I didn't want to use the key in the HTML so I made a config.js file so I could reference it from there instead.

<script src="main.js"></script>
<script src="config.js"></script>
var token = '12345'

Later, I have to reference in key in the URL and I tried doing this:

<script async defer
  src=`https://maps.googleapis.com/maps/api/js?key=${token}&callback=initMap`>
 </script>

The URL is underlined red, but shows no error message. I was wondering how I would go about doing this. Thanks!

CodePudding user response:

Construct the <script> tag dynamically in JavaScript once you have the token.

const script = document.body.appendChild(document.createElement('script'));
script.src = `https://maps.googleapis.com/maps/api/js?key=${token}&callback=initMap`;

CodePudding user response:

Make an html element in javascript and append it to the head Index.html:

<script defer src="scriptTagConfig.js"></script>

scriptTagConfig.js:

//Create element
const apiScriptTag = document.createElement("script")

//Set src attribute
apiScriptTag.setAttribute("src",`https://maps.googleapis.com/maps/api/js?key=${token}&callback=initMap`)

//Append to DOM
document.head.appendChild(apiScriptTag)
  • Related