Martin Green Martin Green - 1 year ago 88
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 async defer

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 Source

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";

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 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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download