简体   繁体   中英

Passing Javascript global variable in HTML's <script> src attribute

I have the following script in my HTML head element.

<script src="" id="mapScriptID" type="text/javascript"></script>
<script type="text/javascript">
    var resloc = "http://maps.google.com/maps/api/js?sensor=true&key="+key;
    var mapScript = document.getElementById('mapScriptID');
    mapScript.src = resloc;
</script>  

The reason for it is that I would like the key value for the google map api to be defined in once only as I am using it in multiple places in my application. So that in the future when the key value changes I only have to change it in one place. But now for some reason the application is not seeing the google map api anymore. It's giving me ' google is not defined ' message when I call google.maps.LatLng(....);

it previously used to be

 <script src="http://maps.google.com/maps/api/js?sensor=true&key=xxxxxxxxxxxxxxxxxxxxxxxx" type="text/javascript"></script>

And it worked completely fine.

After trying multiple solutions. Eventually I used JQuery's $.getScript() method which worked sufficiently well in my scenario.

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