简体   繁体   English

如何延迟页面直到 DOM 操作完成?

[英]How to delay page until DOM manipulation has been completed?

I created a very minimal teaser page with a counter written in pure Javascript (no jQuery etc.).我用纯 Javascript(没有 jQuery 等)编写的计数器创建了一个非常小的预告页面。

This is my HTML:这是我的 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>

This is my Javascript:这是我的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);

It works pretty well.它工作得很好。 However, when the page loads, it starts with an empty line and about a second later, the countdown is displayed.但是,当页面加载时,它以空行开头,大约一秒钟后,将显示倒计时。

Is there a way to avoid that behavior?有没有办法避免这种行为? I'd like to show the countdown right from the start, even if this means to delay the display of the whole page until the DOM is ready.我想从一开始就显示倒计时,即使这意味着要延迟整个页面的显示,直到 DOM 准备好。

At the moment, the JS-code is located in an external file.目前,JS 代码位于外部文件中。 I load this file at the end of the <body> .我在<body>的末尾加载这个文件。 I also placed it ant the end of the <head> with no difference.我还把它放在<head>的末尾,没有任何区别。

Any help is greatly appreciated!任何帮助是极大的赞赏!

Obviously your Javascript is loaded after your HTML is loaded.显然,您的 Javascript 是在您的 HTML 加载后加载的。 Put your code into the <head> section:将您的代码放入<head>部分:

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

... it needs window.onload too (thanks to Kaddath). ...它也需要 window.onload(感谢 Kaddath)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM