javascriptjqueryhtmlajax

Using JavaScript to create a <script src=...> element breaks the API that I'm trying to use


At the top of one of my HTML files there is this line:

<script src="//maps.google.com/maps/api/js?key=apikey"></script>

This API key is currently hard-coded into the file, and I want to instead use a config option defined in a .cfg file elsewhere. However, I can't get any sort of variable into the src attribute of the script element.

I have tried:

<script>
    document.createElement('script')).src='//maps.google.com/maps/api/js?key=apikeybutvariable'; 
</script>

and

<script>
  $('<script>').attr({
    src: '//maps.google.com/maps/api/js?key=apikeybutvariable',
    type: 'text/javascript'}).appendTo('body')
</script>

When I try either of these the next script element can't see the content defined by the Google Maps JS API.
What's going on here, and how do I fix it?


Solution

  • If you’re trying to use the functionality defined in the JavaScript file right after it won’t work. It hasn’t been loaded yet. JavaScript is synchronous: any modification to the DOM is only acted upon by the browser after your code finishes. This means loading the file happens only after your code finishes and only after it has been loaded you can use what’s defined in it. The loading also takes time and appending it to the body means it’s loaded at the end while your other code is before it.

    Either use a ready made dynamic loader or attach an event to the script tag to call a function after it has been loaded. Then you know when it’s available for use.