[英]Pre-load javascript
我有一個腳本來加載時間和日期等。我將結果加載到一個 div 中,並且該 div 有一個輸入 CSS3 animation。 唯一的問題是實際加載時間和日期需要幾秒鍾,它只是突然出現。 由於您在加載頁面時沒有立即看到它,因此您甚至看不到 animation,因為它在腳本加載時已經結束。
所以我的問題是:是否可以將頁面加載延遲到加載時間和日期腳本之后?
免責聲明:這是一個純粹的實驗/創意項目,我正在從事因此我不擔心效率。
腳本:
<script>
var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December")
function getthedate(){
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn="AM"
if (hours>=12)
dn="PM"
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
//change font size here
var cdate="<div class='ref'><span>"+hours+":"+minutes+"</span> "+dn+"</div>"+dayarray[day]+", "+montharray[month]+" "+daym+", "+year+""
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("time-date").innerHTML=cdate
else
document.write(cdate)
}
if (!document.all&&!document.getElementById)
getthedate()
function goforit(){
if (document.all||document.getElementById)
setInterval("getthedate()",1000)
}
</script>
HTML:
<body onLoad="goforit()">
<div id="time-date"></div>
</body>
您的代碼在加載數據之前顯式等待一秒鍾。 您應該在setInterval()
語句之前立即調用getthedate()
:
if (document.all||document.getElementById)
getthedate()
setInterval("getthedate()",1000)
}
這可以避免阻止頁面加載的需要。 如果這還不夠,您將需要將代碼內聯而不是通過僅在整個頁面加載后運行的onload
調用它。
您正在從body onload
事件調用腳本,因此根據定義,它將等到頁面完全加載。
如果您希望腳本更早運行,您可以在 HTML 中放置一個腳本標簽,該標簽在 position 處調用goforit()
function,但結果可能不會更好
<div id="time-date"></div>
<script type='text/javascript'>
goforit();
</script>
將此腳本放在您的 div 下方。 您的 div 必須在執行腳本之前加載。
<script type='text/javascript'>
goforit();
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.