Search code examples
javascriptarrayses6-promisenodelist

Content download synchronization


I have four html-elements, in which at different speeds from the server comes a different amount of content (text and images). How can i show their contents only after all the content has come to all elements?

I want to initially show placeholders, and remove them only when I have all content ready to show for user.


Solution

  • While i find this random image API painfully slow, it is good for a demonstration. You may approach as follows;

    var imgPrs = Array.from({length: 4})
                      .map(_ => fetch("https://unsplash.it/300/400/?random").then(res => res.blob()));
    Promise.all(imgPrs)
      .then(blob => document.querySelectorAll("#container img")
                            .forEach((img, i) => img.src = (window.URL || window.webkitURL).createObjectURL(blob[i])));
    #container {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-evenly;
      align-items: center;
      width: 80vw;
      height: 60vw;
      background-color: #000;
      box-sizing: border-box;
    }
    
    .tl {
      width: 45%;
      height: 45%;
      background-color: #ccc;
    }
    
    .tr {
      width: 45%;
      height: 45%;
      background-color: #bbb;
    }
    
    .bl {
      width: 45%;
      height: 45%;
      background-color: #aaa;
    }
    
    .br {
      width: 45%;
      height: 45%;
      background-color: #999;
    }
    <div id="container">
      <img class="tl">
      <img class="tr">
      <img class="bl">
      <img class="br">
    </div>