在页面加载时加载外部javascript
在我的网站的页脚,我想显示一个地图,因为地图加载了大量的船图标,位于那里的位置,它减慢了页面加载,甚至在我的本地机器上。代码正好放在结束正文标记之前 加载地图所需的代码可以通过添加一组变量进行缩放:在页面加载时加载外部javascript,javascript,html,Javascript,Html,在我的网站的页脚,我想显示一个地图,因为地图加载了大量的船图标,位于那里的位置,它减慢了页面加载,甚至在我的本地机器上。代码正好放在结束正文标记之前 加载地图所需的代码可以通过添加一组变量进行缩放: <script> width='100%'; // the width of the embedded map in pixels or percentage height='300'; // the height of the embedded map in pixels
<script>
width='100%'; // the width of the embedded map in pixels or percentage
height='300'; // the height of the embedded map in pixels or percentage
border='1'; // the width of the border around the map (zero means no border)
shownames='true'; // to display ship names on the map (true or false)
latitude='51.7143'; // the latitude of the center of the map, in decimal degrees
longitude='04.0889'; // the longitude of the center of the map, in decimal degrees
zoom='11'; // the zoom level of the map (values between 2 and 17)
maptype='0'; // use 0 for Normal Map, 1 for Satellite, 2 for OpenStreetMap
trackvessel='' //244770624'; MMSI of a vessel (note: vessel will be displayed only if within range of the system) - overrides "zoom" option
fleet=''; // the registered email address of a user-defined fleet (user's default fleet is used)
Read more at http://www.marinetraffic.com/en/p/embed-map#6YXCVvOUaBxYHgoT.99
</script>
<script type="text/javascript" src="https://www.marinetraffic.com/js/embed.js"></script>
为了克服页面加载的问题,我想出了在页面加载时加载脚本的想法。已经尝试过异步或延迟,但是这会破坏功能
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "http://www.marinetraffic.com/js/embed.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
我对Javascript不太熟悉,无法理解为什么embed.js脚本无法加载。它也应该在没有变量的情况下加载
有人愿意为我指出正确的方向吗?我想你有这个onload脚本来加载embed.js吗?这可能是问题所在,因为加载脚本时没有任何body元素。在正文结束前保留脚本 或者您可以尝试:
document.getElementsByTagName('body')[0].appendChild(element);
无论如何,defer和async也会这样做
编辑:
在页脚上或在关闭body标记之前,您可以等待页面加载并执行此简单函数
<script type="text/javascript">
window.onload = function() {
var tag = document.createElement('script');
tag.src = 'http://www.marinetraffic.com/js/embed.js';
document.body.appendChild(tag);
}
</script>
我不知道为什么async或defer不适合您?也许它起作用了?您可以随时检查代码行何时执行。您可以将onload属性用于console.log或在脚本标记中发出警报,以检查何时加载了资源。谢谢您的回复。脚本要在结束body标记之前加载,并且也定位在那里。我会试试你的建议的。我试过了一个愚蠢的建议,但运气不好。也没有错误。所以我只能猜测这背后的原因是,您正在尝试异步方式,首先完全加载文档,以后无法写入任何内容。嗯,这是我无法解决的问题。是否有其他方法可以实现相同的功能?请检查我的答案。我编辑了更多的信息。希望能有帮助。