Martin Green Martin Green - 3 months ago 7
HTML Question

How do I convert HTML + JavaScript to external Javascript

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?

Answer

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 http://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)