How do I convert HTML + JavaScript to external Javascript

时间:2022-10-30 13:16:00

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

我试图将html和javascript代码转换为html文件可以执行的外部代码文件。

Here is the code in HTML:

这是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?

我知道如何将函数放入外部javascript代码文件,但我的问题是如何将第二个脚本标记放入外部javascript?

1 个解决方案

#1


0  

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

你不能在javascript中放置标签。您可以创建一个标签并将其插入到html中。

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.

这将创建一个脚本标记,其src属性设置为“/test.js”,并将其附加到head标记的末尾。

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

有关实现此目的的更多方法,请参阅https://*.com/a/950146。

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)

如果您的目标是更好地清理和管理您的javascript文件,我建议使用其中一个模块化的JavaScript管理库。 (例如RequireJS)

#1


0  

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

你不能在javascript中放置标签。您可以创建一个标签并将其插入到html中。

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.

这将创建一个脚本标记,其src属性设置为“/test.js”,并将其附加到head标记的末尾。

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

有关实现此目的的更多方法,请参阅https://*.com/a/950146。

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)

如果您的目标是更好地清理和管理您的javascript文件,我建议使用其中一个模块化的JavaScript管理库。 (例如RequireJS)