我有一个脚本来加载时间和日期等。我将结果加载到div中,并且该div有一个输入CSS3动画。唯一的问题是,实际加载的时间和日期需要几秒钟才能突然出现。由于您在加载页面时没有立即看到它,因此您甚至看不到动画,因为它在脚本加载时已经结束。
所以我的问题是:是否有可能延迟页面加载,直到加载时间和日期脚本?
免责声明:这是我正在研究的纯粹实验/创意项目,所以我并不担心效率。
脚本:
<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>
答案 0 :(得分:1)
在加载数据之前,您的代码会显式等待一秒钟。您应该在getthedate()
声明之前立即致电setInterval()
:
if (document.all||document.getElementById)
getthedate()
setInterval("getthedate()",1000)
}
这可以避免阻止页面加载的需要。如果这还不够,您需要将代码内联,而不是通过onload
调用代码,{{1}}仅在整个页面加载后运行。
答案 1 :(得分:0)
您正在调用body onload
事件中的脚本,因此根据定义,它将等待页面完全加载。
如果您希望脚本能够提前运行,您可以在HTML中放置一个脚本标记,在您希望解析的位置调用goforit()
函数,但结果可能不会更好。
<div id="time-date"></div>
<script type='text/javascript'>
goforit();
</script>
答案 2 :(得分:0)
将此脚本放在div下面。您的div必须在执行脚本之前加载。
<script type='text/javascript'>
goforit();
</script>