如何将页面延迟到DOM操作完成之前?

时间:2019-01-21 11:19:08

标签: javascript html

我创建了一个非常小的预告页面,并带有一个用纯Javascript(没有jQuery等)编写的计数器。

这是我的HTML:

<!DOCTYPE html>
<html>
  <head>
    <script language="JavaScript" type="text/javascript" src="countdown.js"></script>
  </head>
<body>
  <h1>Countdown:</h1>
  <p id="counter"></p>
</body>
</html>

这是我的Javascript:

// Set the date we're counting down to
var countDownDate = new Date("Sep 01, 2019 10:00:00").getTime();

// Update the count down every 1 second
var countdownfunction = setInterval(function() {

    // Get todays date and time, calculate distance
    var now = new Date().getTime();
    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("counter").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

    // If the count down is over, write some text 
    if (distance < 0) {
        clearInterval(countdownfunction);
        document.getElementById("counter").innerHTML = "EXPIRED";
    }
}, 1000);

效果很好。但是,当页面加载时,它以空行开始,大约一秒钟后,显示倒计时。

有没有办法避免这种行为?我想从一开始就显示倒计时,即使这意味着将整个页面的显示延迟到DOM准备就绪为止。

目前,JS代码位于外部文件中。我在<body>的末尾加载了该文件。我还把它放在<head>的末尾,没有区别。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

很明显,在加载HTML之后,就加载了Javascript。将您的代码放入<head>部分:

<script>
    window.onload = function () {
        document.getElementById("counter").innerHTML = hours + "h " + minutes + "m ";
    };
</script>

...它也需要window.onload(感谢Kaddath)。