隐藏元素直到页面完全加载

Hide elements until page is fully loaded

我想要一个普通的 JS 代码,它隐藏所有页面元素(加载微调器除外)直到页面完全加载,然后删除或隐藏加载微调器元素。我的代码在加载页面后隐藏微调器方面做得很好,但我无法完成另一部分。它看起来像这样:

function hideloader() {
  document.getElementById("loading").style.display="none";
}
<html>
  <head>
    <title>My Title</title>
    <link href="main.css" rel="stylesheet" type="text/css"/>
    <script src="script.js"></script>
  </head>
  <body onload="hideloader()">
    <div id="loading">
      <!--All loading spinner design goes here-->
      Loading...
    </div>
    <header>
      <!--Header stuff-->
      <h1>My Title</h1>
    </header>
    <p>
      <!--Main content-->
      My content
     </p>
    <footer>
      <!--footer stuff-->
      Footer stuff
     </footer>
  </body>
</html>
提前致谢!

一般来说,最好不要这样做,而是设计页面,让渐进式加载为用户提供一些内容,同时等待页面的其余部分。

但做起来很简单:只需将主要内容放在一个元素(例如 div)中,上面有 class(例如 hidden),并在要显示时删除 class:

CSS:

.hidden {
    display: none;
}

JavaScript当你准备好展示它时:

document.getElementById("content").classList.remove("hidden");

(classList 被所有现代浏览器支持;如果你需要支持旧浏览器,它可以被 polyfilled 或者,删除所有 classes,只需要 .className = ""。 )


另一种方法是在加载时向 body 添加一个 class,然后在加载期间对要 show/hide 的各种元素添加 classes,使用CSS 像这样:

body:not(loaded) .hide-for-load {
  display: none;
}
body.loaded .hide-after-load {
  display: none;
}

然后 .hide-for-load 个元素将被隐藏,直到您添加 class,并且 .hide-after-load 个元素将在您添加类时被隐藏。

来自您页面的实时示例:

setTimeout(function() {
  document.body.classList.add("loaded");
}, 1000);
body:not(.loaded) .hide-for-load {
  display: none;
}
body.loaded .hide-after-load {
  display: none;
}
<div id="loading" class="hide-after-load">
  Loading<!--All loading spinner design goes here-->
</div>
<header class="hide-for-load">
  <!--Header stuff-->
  <h1>My Title</h1>
</header>
<p class="hide-for-load">
  <!--Main content-->
  My content
</p>
<footer class="hide-for-load">
  <!--footer stuff-->
  Footer stuff
</footer>