Как улучшить скорость загрузки api JSON или иконку загрузки? - PullRequest
0 голосов
/ 07 марта 2019

Как следует из названия. Как улучшить скорость загрузки JSON для API fetch специально для комментариев.

Попытка сохранить Javascript для ES6.

Когда вы нажимаете «сообщение», оно запускает функции getSelectedPost и GetComments. Почему загрузка JSON-файла комментариев происходит так медленно? Это потому, что это просто большой файл?

Что-нибудь, что я могу добавить, чтобы улучшить производительность и / или значок потенциальной загрузки?

Спасибо

getPosts();

document.addEventListener('click', function (event) {
    if (event.target.matches('.post') || event.target.parentElement.matches('.post')) {
      const postId = event.target.getAttribute('data-postid') || event.target.parentElement.getAttribute('data-postid');  
      getSelectedPost(postId);
      getComments(postId);
    }
})

function getPosts(){
    const posts = 'https://jsonplaceholder.typicode.com/posts';

    fetch(posts)
      .then(response => response.json())
      .then(data => {
      for (const post of data){

        const markup = `
          <div class="post" data-postid="${post.id}">
            <span class="title">${post.title}</span>
            <p>${post.body}</p>
          </div>
        `;
        
        document.getElementById('back').style.display = 'none';
        const grid = document.querySelector('.grid');
        grid.innerHTML += "";
        grid.innerHTML += markup;
      }
    })
      .catch((err) => {
      console.error(err);
    })
}

function getSelectedPost(postId){  
    const postSingle = "https://jsonplaceholder.typicode.com/posts/" + postId;
    
    fetch(postSingle)
      .then(response => response.json())
      .then(data => {

        const markup = `
          <div class="post active" data-postid="${data.id}">
            <span class="title">${data.title}</span>
            <p>${data.body}</p>
          </div>
        `;
        
        document.getElementById('back').style.display = 'block';
        const single = document.querySelector('.single');
        const grid = document.querySelector('.grid');
        grid.innerHTML = "";
        single.innerHTML = "";
        single.innerHTML = markup;
    })
      .catch((err) => {
      console.error(err);
    })
}

function getComments(postId){
    const postComments = "https://jsonplaceholder.typicode.com/posts/" + postId + "/comments";
    console.log(postComments)
    
    fetch(postComments)
      .then(response => response.json())
      .then(data => {
        for (const comment of data){

          const markup = `
          <div class="comment" data-commentid="${comment.id}">
          <span class="name">${comment.name}</span>
          <a href="${comment.email}" class="email">${comment.email}</a>
          <p>${comment.body}</p>
          </div>
          `;

          const comments = document.querySelector('.comments');
          comments.innerHTML += "";
          comments.innerHTML += markup;
        }
    })
      .catch((err) => {
      console.error(err);
    })
}

document.getElementById('back').addEventListener('click', getPosts);
body {
  font-family: roboto;
}

#back {
  display: none;
  margin-bottom: 1rem;
  cursor: pointer;
}

.container {
    max-width: 78.75rem;
    width: 100%;
    margin: 0 auto;
    padding: 0 1rem;
}

.grid {
  display: grid;
  grid-gap: 1rem;
  grid-template-columns: repeat(5, 1fr);
}

.post {
  background-color: #ccc;
  padding: 1.5rem;
  transition: all .3s;
}

.post:hover, .post.active {
  background-color: black;
  color: white;
  cursor: pointer;
}

.post.active {
  margin-bottom: 1rem;
}

.post.active:hover {
  cursor: default;
}

.title, .name {
  font-weight: bold;
}
<div class="container">
    <button id="back">Back</button>
    <div class="grid"></div>
    <div class="single"></div>
    <div class="comments"></div>
</div>

1 Ответ

1 голос
/ 07 марта 2019

Я думаю, одна из вещей, которую вы должны реорганизовать, это использовать innerHTML, в приведенном ниже коде я просто использовал его один раз.

getPosts();

document.addEventListener('click', function (event) {
    if (event.target.matches('.post') || event.target.parentElement.matches('.post')) {
      const postId = event.target.getAttribute('data-postid') || event.target.parentElement.getAttribute('data-postid');  
      getSelectedPost(postId);
      getComments(postId);
    }
})

function getPosts(){
    const posts = 'https://jsonplaceholder.typicode.com/posts';

    fetch(posts)
      .then(response => response.json())
      .then(data => {
      let grid = '';
      for (const post of data){

        const markup = `
          <div class="post" data-postid="${post.id}">
            <span class="title">${post.title}</span>
            <p>${post.body}</p>
          </div>
        `;
        
        document.getElementById('back').style.display = 'none';
        grid += markup; 
      }
      return grid;
    }).then((grid) => {
      document.querySelector('.grid').innerHTML = grid;
    })
      .catch((err) => {
      console.error(err);
    })
}

function getSelectedPost(postId){  
    const postSingle = "https://jsonplaceholder.typicode.com/posts/" + postId;
    
    fetch(postSingle)
      .then(response => response.json())
      .then(data => {

        const markup = `
          <div class="post active" data-postid="${data.id}">
            <span class="title">${data.title}</span>
            <p>${data.body}</p>
          </div>
        `;
        
        document.getElementById('back').style.display = 'block';
        const single = document.querySelector('.single');
        const grid = document.querySelector('.grid');
        grid.innerHTML = "";
        single.innerHTML = "";
        single.innerHTML = markup;
    })
      .catch((err) => {
      console.error(err);
    })
}

function getComments(postId){
    const postComments = "https://jsonplaceholder.typicode.com/posts/" + postId + "/comments";
    console.log(postComments)
    
    fetch(postComments)
      .then(response => response.json())
      .then(data => {
      let comments = '';
        for (const comment of data){

          const markup = `
          <div class="comment" data-commentid="${comment.id}">
          <span class="name">${comment.name}</span>
          <a href="${comment.email}" class="email">${comment.email}</a>
          <p>${comment.body}</p>
          </div>
          `;

          
          comments += markup;
        }
      return comments;
    }).then((comments) => {
      document.querySelector('.comments').innerHTML = comments;
    })
      .catch((err) => {
      console.error(err);
    })
}

document.getElementById('back').addEventListener('click', getPosts);
body {
  font-family: roboto;
}

#back {
  display: none;
  margin-bottom: 1rem;
  cursor: pointer;
}

.container {
    max-width: 78.75rem;
    width: 100%;
    margin: 0 auto;
    padding: 0 1rem;
}

.grid {
  display: grid;
  grid-gap: 1rem;
  grid-template-columns: repeat(5, 1fr);
}

.post {
  background-color: #ccc;
  padding: 1.5rem;
  transition: all .3s;
}

.post:hover, .post.active {
  background-color: black;
  color: white;
  cursor: pointer;
}

.post.active {
  margin-bottom: 1rem;
}

.post.active:hover {
  cursor: default;
}

.title, .name {
  font-weight: bold;
}
<div class="container">
    <button id="back">Back</button>
    <div class="grid"></div>
    <div class="single"></div>
    <div class="comments"></div>
</div>
...