0

I am trying to convert html and javascript code to an external code file that the html file can execute.

Here is the code in HTML:

function initMap() {
        var mapDiv = document.getElementById('map');
        var map = new google.maps.Map(mapDiv, {
            center: {lat: 44.540, lng: -78.546},
            zoom: 8
        });
      }
    </script>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">

I know how to place the function into the external javascript code file, but my problem is how do I place the second script tag into external javascript?

Martin Green
  • 27
  • 1
  • 2
  • 6
  • 2
    You don't have to, why do you want to do that? – iomv Aug 10 '16 at 14:45
  • 1
    what do you mean by "external javascript code file"? do you mean a .js file which can be included in another HTML, or something else? – some1 Aug 10 '16 at 14:48
  • Yes I mean a .js file. @MarcoValente, I want to do this to clear up my html file and code. I want for others to be able to just go into the .js file and make changes instead of having to hunt through code. – Martin Green Aug 10 '16 at 14:49
  • The second `script` is an HTML tag - you keep that in the HTML... unless you want to lazy load it. – tymeJV Aug 10 '16 at 14:51

1 Answers1

0

You can not place tags inside javascript. You can create a tag and insert it into html however.

var script = document.createElement("script");
script.src = "/test.js";
document.body.appendChild(script);

This will create a script tag with its src attribute set to "/test.js" and append it to the end of the head tag.

See https://stackoverflow.com/a/950146 for more ways to achieve this.

If your aim is to clean up and manage your javascript files better, I suggest using one of the modular javascript management libraries. (e.g. RequireJS)

Community
  • 1
  • 1
Ozan
  • 3,709
  • 2
  • 18
  • 23