[英]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. 我正在尝试将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中?
You can not place tags inside javascript. 您不能在javascript中放置标签。 You can create a tag and insert it into html however. 您可以创建标签并将其插入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. 这将创建一个script
标签,其src
属性设置为“ /test.js”,并将其附加到head
标签的末尾。
See https://stackoverflow.com/a/950146 for more ways to achieve this. 有关更多信息,请参见https://stackoverflow.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. 如果您的目标是更好地清理和管理 javascript文件,建议您使用一种模块化javascript管理库。 (eg RequireJS ) (例如RequireJS )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.