簡體   English   中英

在頁面加載時加載外部 javascript

[英]Load external javascript on page load

在我網站的頁腳中,我想顯示一張來自MarineTraffic的地圖,因為該地圖加載了大量的船圖標,定位了那里的位置,即使在我的本地機器上,它也會減慢頁面加載速度。 代碼放在結束 body-tag 之前。

加載地圖所需的代碼可以通過添加一組變量來縮放:

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

克服了頁面加載的發現,我想出了在頁面加載時加載腳本的想法。 已經嘗試過 async 或 defer,但這會破壞功能。

<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 嗎? 這可能是問題所在,因為當腳本加載時沒有任何正文元素。 在正文結束之前保留您的腳本。

或者你可以試試:

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或在腳本標記中發出alert以檢查資源何時加載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM