Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

javascript - Prioritise a div or image to load first

Here's some example code, I would like to prioritise "div1" to load before anything else does.

<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>
question from:https://stackoverflow.com/questions/65900593/prioritise-a-div-or-image-to-load-first

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just via HTML you cannot prioritize what will load first on your web page.

The page loads from the Top to Down approach, which first <HEAD> and its content, then <BODY> and its content.

If you like to render a page according to your need you need to use JavaScript.

Below sample code below does the same.

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...