优先加载 div 或图像

Prioritise a div or image to load first

这是一些示例代码,我想优先加载“div1”,然后再加载其他任何东西。

<HTML>
<body>
<div id="div1">This div will load first please</div>
<img src="/" title="Other large images">
<img src="/" title="Other large images">
<img src="/" title="Other large images">
<img src="/" title="Other large images">
<img src="/" title="Other large images">
</body>
</html>

仅通过 HTML 您无法确定首先加载到您网页上的内容的优先级。

页面从 从上到下 方法加载,首先是 <HEAD> 及其内容,然后是 <BODY> 及其内容。

如果您想根据需要呈现页面,则需要使用 JavaScript。

下面的示例代码也是如此。

window.onload = function(){
   
   const div1 = `<div id="div1">This div will load first please</div>`;
   setTimeout(() => {
     console.log("DIV1 load after 3 second");
     document.getElementById("the-div-1").innerHTML = div1;
   }, 3000); 
   
   const imgs = `
      <img src="https://picsum.photos/id/237/200/300.jpg" title="Other large images">
      <br />
      <img src="https://picsum.photos/id/238/200/300.jpg" title="Other large images">
      <br />
      <img src="https://picsum.photos/id/237/200/300.jpg" title="Other large images">
      <br />
      <img src="https://picsum.photos/id/240/200/300.jpg" title="Other large images">
      <br />
      <img src="https://picsum.photos/id/241/200/300.jpg" title="Other large images">
      <br />
   `;

  setTimeout(() => {
     console.log("Images load after 6 second");
     document.getElementById("image-div").innerHTML = imgs;
   }, 6000); 
}
<html>

<body>
  <div>
    <span>Anything in HTML file will load from top-down apporach.</span>
  </div>
  
  <div id="the-div-1"></div>
  
  <div id="image-div"></div>
  
</body>

</html>

使用document.onload
Documentation

<div id="a"><!--other stuff--></div>
<div onload="loadOtherContent()">IMPORTANT DIV</div>
<div id="b"><!--other stuff--></div>
<script>
const loadOtherContent = () => {
    //load those other stuff
    document.getElementById("a").innerHTML = "...";
    document.getElementById("b").innerHTML = "...";
    //...
}
</script>