Search code examples
javascripthtmlasynchronousfetchsynchronous

Script tag not rendering synchronously


this is the code im working with

<body>

  <script type="text/javascript" src = "http://localhost:3000/common_assets/navbar.js"></script>

  <script type="text/javascript" src = "http://localhost:3000//index.js"></script>

  <h1>MonkaHmm...</h1>

</body>

both the scripts render html and they both work the problem is the second script is always rendered last so the MonkaHmm... comes in at the middle of the page.

this is the code thats in the second script tag

async function cardData(){
    var response = await fetch('http://localhost:3000/Board_Members.json');
    var carddata =  await response.json();

    carddata.forEach(function(membercard){
      var member_cards = document.createElement("div");
      var code = `
        <div class="member_cards card-4">
          <img class = "img_member" src="http://localhost:3000/IMAGES/jonipic.jpg">
          <div class="description">
            <h5>${membercard.name}</h5>
            <h5>${membercard.title}</h5>
            ${membercard.description}
          </div>

        </div>
        <link rel="stylesheet" type="text/css" href="http://localhost:3000/index.css">
`
      member_cards.innerHTML = code;
      document.body.appendChild(member_cards);
    });
}

cardData();

i have a feeling this is happening because of the fetch but its in an async/await function so i thought it would act synchronously but to be honest i have no clue. HELP my fellow pepega coders


Solution

  • When you call cardData() it does invoke the async function and return a promise. The browser doesn't wait for the response to continue rendering the page.

    You could create the member_cards div or a placeholder and append it before you do your async calls and add your cards to it when you get the response.