简体   繁体   中英

How to append parts to an inline script URL using JavaScript?

I have a script (Google Maps, to be exact) that is loading dynamically, and for a couple of reasons, I cannot alter how this initially loads by default.

Through JavaScript, I would like to find the string libraries=places and change it to libraries=places,visualization after the fact

So, the originally output:

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

Would be:

<script type="text/javascript" 
          src="https://maps.googleapis.com/maps/api/js?libraries=places,visualization">
</script>

Is this even possible?

Thanks In Advance

this solution should apply to yours as well: How do I include a JavaScript file in another JavaScript file?

script.src = url; will be the line where you add the src url however you like

First of all Give the google map script tag an ID:

<script id="google_map_script" type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>

Then do:

var google_map_script = document.getElementById("google_map_script")
google_map_script.setAttribute("src", "https://maps.googleapis.com/maps/api/js?libraries=places,visualization")

Edit: since apparently this isn't what is needed then what about this:

var script = document.createElement('script');

my_awesome_script.setAttribute('src','https://maps.googleapis.com/maps/api/js?libraries=places,visualization');

document.head.appendChild(script);

Also have a look into using postscribe .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM