[英]Inclusion of a js file in HTML
我在HTML中包含一個巨大的javascript文件(500K)。 有沒有一種聰明的方法來知道它是否已經加載。 我能想到的一種方法是在其構造函數中有一個變量來初始化並通知我。 加載是異步的,在包含該JS函數之前,我無法繼續進行。
謝謝
通過使用jQuery,您可以處理在加載腳本文件時運行的回調函數:
$.getScript("yourScriptFile.js", function(){
// What to do when the script is loaded
});
為了澄清奧斯卡的答案:
<script type='text/javascript' src='script.js'></script>
<script type='text/javascript'>
alert('the file has loaded!');
//Anything here will not be executed before the script.js was loaded
</script>
同樣,如果文件很大,則最好在頁面加載后加載它,以便在連接速度較慢的情況下可以在頁面加載之前使用頁面:
<head> <script type='text/javascript' src='script.js'></script> </head> <body> Nothing here will be rendered until the script has finished loading </body>
更好的是:
<head> </head> <body> I will be rendered immidiatly </body> <script type='text/javascript' src='script.js'></script> </html>
這樣,用戶可以快速獲取頁面,然后才需要等待javascript功能。
<SCRIPT LANGUAGE="JavaScript" SRC="filename">
</SCRIPT>
??
您是否嘗試壓縮javascript文件? 將某些功能移到單獨的Javascript文件中,僅包括所需的JavaScript?
您可以在腳本文件的末尾調用一個函數,該函數將通知頁面上的腳本可以使用了。
也許這個問題可能會被重述:我怎么知道我的腳本被加載到html頁面中? 將腳本放在頁面底部,確保所有DOM元素都可用於腳本。 當您想知道腳本是否可用時,應檢查要運行的功能是否可用。 也許這個構造函數可以幫助您:
function Wait(what,action,id){
var _x = this,
rep = document.getElementById('report'),
cnt = 0,
timeout = 5,
interval = 100;
_x.id = id;
if (!(what instanceof Function)) {
return true; //or say something about it
}
function dowait() {
cnt += interval;
if (what())
{
clearInterval(_x.iv);
action();
return true;
}
if (cnt>(timeout*1000))
{
clearInterval(_x.iv);
//[do some timeout-action]
return true;
}
}
_x.iv = setInterval(dowait,interval);
}
構造函數將一個函數(返回布爾值)作為其第一個參數。 喜歡
function(){return document.getElementById('someelement').innerHTML = '';}
因此,如果您在JavaScript之前添加了此代碼,則可以執行以下操作:
var testfn =
function(){return document.getElementById('someElement').innerHTML = '';},
callback =
function(){alert('someElement is empty')},
dummy = null;
window.onload=function(dummy=new Wait(testfn,calllback);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.