Home  >  Q&A  >  body text

How can I deconstruct a json file to display all the content in the site? Every time I load everything at once I get thousands of objects and chrome crashes

Every time I load everything at once I get thousands of objects and chrome crashes.

btn.addEventListener('click', function(){
    event.preventDefault();

async function getData(){
    const response=await fetch(url)
    const data= await response.json();
    info(data)
}

getData();

function info(x){
    x.messages.forEach(element => {
        console.log(element.creator.name+": "+element.text)
    // console.log(x.element.text)
    con.innerHTML += "<p>"+element.creator.name+": "+element.text+"</p>";
    });
}

This is my code using rn

P粉545682500P粉545682500245 days ago437

reply all(2)I'll reply

  • P粉463291248

    P粉4632912482024-02-18 12:17:20

    The first innerhtml is very slow because it needs to be parsed every time. Create a function to create a Dom element and attach it to the desired container. Adding pagination or processes to insert data in chunks would also help.

    reply
    0
  • P粉121081658

    P粉1210816582024-02-18 12:03:20

    Try to use appending child elements to load one element at a time. I've left an alternative code here.

    sandbox

    Code

    const btn = document.getElementById("BtnInfo");
    btn.addEventListener("click", function (event) {
      event.preventDefault();
    
      async function getData() {
        const response = await fetch("https://dummyjson.com/products/1");
        const data = await response.json();
    
        info(data);
      }
    
      getData();
    
      function info(x) {
        for (let key in x) {
          var pElement = document.createElement("p");
          pElement.textContent = `${key}: ${x[key]}`;
          document.body.appendChild(pElement);
        }
      }
    });
      
        
      

    reply
    0
  • Cancelreply