Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change the script src?

I'm trying to dynamically change the region depends on what I select in a dropdown field.

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?region=DK"></script>

Can someone help me figure this out?

like image 295
james Avatar asked Aug 01 '26 05:08

james


2 Answers

You can load JavaScript dynamically after page has loaded, but remember: once you've loaded it, you can't unload JavaScript in an active page. It is stored in the browsers memory pool. You can reload a page, which will clear the active scripts, and start over. Alternatively you could override the functions that you've got set.

With this said. Here's how to change the script after page load with javascript:

<select onChange="changeRegion(this.value);">
    <option value="-">Select region</option>
    <option value="SE">Sweden</option>
    <option value="DK">Denmark</option>
</select>

<div id="output">
    <script id="map" type="text/javascript" src="https://maps.googleapis.com/maps/api/js?region=DK"></script>
</div>

<script type="text/javascript">
function changeRegion(value)
{
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "https://maps.googleapis.com/maps/api/js?region=" + value;
    s.innerHTML = null;
    s.id = "map";
    document.getElementById("output").innerHTML = "";
    document.getElementById("output").appendChild(s);
}
</script>
like image 189
henrik Avatar answered Aug 03 '26 17:08

henrik


You should avoid loading the Google Maps API more than once. If possible you should consider leaving out that script tag and instead add it through JavaScript once the dropdown (region) selection has been made.

EDIT:

Let's say you have a dropdown like this:

<select id="regionSelector" onchange="loadGoogleMaps()">
  <option value="">Select region to use Google Maps:</option>
  <option value="DK">Denmark</option>
  <option value="SE">Sweden</option>
</select>

Adding the script would be something like:

function loadGoogleMaps() { 

    var selectedRegion = document.getElementById("regionSelector").value;

    if(selectedRegion === '') {
       return;
    }

    var head= document.getElementsByTagName('head')[0];
    var script= document.createElement('script');
    script.type= 'text/javascript';
    script.src= 'https://maps.googleapis.com/maps/api/js?region=' + selectedRegion;
    head.appendChild(script);
}

More info on async loading of the Google Maps API: https://developers.google.com/maps/documentation/javascript/examples/map-simple-async

like image 37
Ted Nyberg Avatar answered Aug 03 '26 17:08

Ted Nyberg