<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          如果后端API一次返回10萬(wàn)條數(shù)據(jù),前端應(yīng)該如何處理?

          共 13328字,需瀏覽 27分鐘

           ·

          2022-07-05 12:18

          不點(diǎn)藍(lán)字關(guān)注,我們哪來(lái)故事?


          最近,我的一位朋友在面試時(shí)被問(wèn)到這個(gè)問(wèn)題。這個(gè)問(wèn)題其實(shí)是考察面試者對(duì)性能優(yōu)化的理解,涉及的話題很多。下面我就和大家一起來(lái)分析一下這個(gè)問(wèn)題。

          創(chuàng)建服務(wù)器

          為了方便后續(xù)測(cè)試,我們可以使用node創(chuàng)建一個(gè)簡(jiǎn)單的服務(wù)器。

          服務(wù)器端代碼:

          const http = require('http')
          const port = 8000;

          let list = []
          let num = 0

          // create 100,000 records
          for (let i = 0; i < 100_000; i++) {
            num++
            list.push({
              src: 'https://miro.medium.com/fit/c/64/64/1*XYGoKrb1w5zdWZLOIEevZg.png',
              text: `hello world ${num}`,
              tid: num
            })
          }

          http.createServer(function (req, res) {
            // for Cross-Origin Resource Sharing (CORS)
            res.writeHead(200, {
              'Access-Control-Allow-Origin''*',
              "Access-Control-Allow-Methods""DELETE,PUT,POST,GET,OPTIONS",
              'Access-Control-Allow-Headers''Content-Type'
            })

            res.end(JSON.stringify(list));
          }).listen(port, function () {
            console.log('server is listening on port ' + port);
          })

          我們可以使用 node 或 nodemon 啟動(dòng)服務(wù)器:

          $ node server.js
          # or 
          $ nodemon server.js

          創(chuàng)建前端模板頁(yè)面

          然后我們的前端由一個(gè) HTML 文件和一個(gè) JS 文件組成。

          Index.html:

          <!DOCTYPE html>
          <html lang="en">
          <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Document</title>
            <style>
              * {
                padding0;
                margin0;
              }

              #container {
                height100vh;
                overflow: auto;
              }

              .sunshine {
                display: flex;
                padding10px;
              }

              img {
                width150px;
                height150px;
              }
          </style>
          </head>
          <body>
              <div id="container">
              </div>
              <script src="./index.js"></script>
          </body>
          </html>

          Index.js:

          // fetch data from the server
          const getList = () => {
            return new Promise((resolve, reject) => {

              var ajax = new XMLHttpRequest();
              ajax.open('get''http://127.0.0.1:8000');
              ajax.send();
              ajax.onreadystatechange = function ({
                if (ajax.readyState == 4 && ajax.status == 200) {
                  resolve(JSON.parse(ajax.responseText))
                }
              }
            })
          }

          // get `container` element
          const container = document.getElementById('container')


          // The rendering logic should be written here.

          好的,這就是我們的前端頁(yè)面模板代碼,我們開(kāi)始渲染數(shù)據(jù)。

          直接渲染

          最直接的方法是一次將所有數(shù)據(jù)渲染到頁(yè)面。代碼如下:

          const renderList = async () => {
              const list = await getList()

              list.forEach(item => {
                  const div = document.createElement('div')
                  div.className = 'sunshine'
                  div.innerHTML = `<img src="${item.src}" /><span>${item.text}</span>`
                  container.appendChild(div)
              })
          }
          renderList()

          一次渲染 100,000 條記錄大約需要 12 秒,這顯然是不可取的。

          通過(guò) setTimeout 進(jìn)行分頁(yè)渲染

          一個(gè)簡(jiǎn)單的優(yōu)化方法是對(duì)數(shù)據(jù)進(jìn)行分頁(yè)。假設(shè)每個(gè)頁(yè)面都有l(wèi)imit記錄,那么數(shù)據(jù)可以分為Math.ceil(total/limit)個(gè)頁(yè)面。之后,我們可以使用 setTimeout 順序渲染頁(yè)面,一次只渲染一個(gè)頁(yè)面。

          const renderList = async () => {

              const list = await getList()

              const total = list.length
              const page = 0
              const limit = 200
              const totalPage = Math.ceil(total / limit)

              const render = (page) => {
                  if (page >= totalPage) return
                  setTimeout(() => {
                      for (let i = page * limit; i < page * limit + limit; i++) {
                          const item = list[i]
                          const div = document.createElement('div')
                          div.className = 'sunshine'
                          div.innerHTML = `<img src="${item.src}" /><span>${item.text}</span>`
                          container.appendChild(div)
                      }
                      render(page + 1)
                  }, 0)
              }
              render(page)
          }

          分頁(yè)后,數(shù)據(jù)可以快速渲染到屏幕上,減少頁(yè)面的空白時(shí)間。

          requestAnimationFrame

          在渲染頁(yè)面的時(shí)候,我們可以使用requestAnimationFrame來(lái)代替setTimeout,這樣可以減少reflow次數(shù),提高性能。

          const renderList = async () => {
              const list = await getList()

              const total = list.length
              const page = 0
              const limit = 200
              const totalPage = Math.ceil(total / limit)

              const render = (page) => {
                  if (page >= totalPage) return

                  requestAnimationFrame(() => {
                      for (let i = page * limit; i < page * limit + limit; i++) {
                          const item = list[i]
                          const div = document.createElement('div')
                          div.className = 'sunshine'
                          div.innerHTML = `<img src="${item.src}" /><span>${item.text}</span>`
                          container.appendChild(div)
                      }
                      render(page + 1)
                  })
              }
              render(page)
          }

          window.requestAnimationFrame() 方法告訴瀏覽器您希望執(zhí)行動(dòng)畫(huà),并請(qǐng)求瀏覽器調(diào)用指定函數(shù)在下一次重繪之前更新動(dòng)畫(huà)。該方法將回調(diào)作為要在重繪之前調(diào)用的參數(shù)。

          文檔片段

          以前,每次創(chuàng)建 div 元素時(shí),都會(huì)通過(guò) appendChild 將元素直接插入到頁(yè)面中。但是 appendChild 是一項(xiàng)昂貴的操作。

          實(shí)際上,我們可以先創(chuàng)建一個(gè)文檔片段,在創(chuàng)建了 div 元素之后,再將元素插入到文檔片段中。創(chuàng)建完所有 div 元素后,將片段插入頁(yè)面。這樣做還可以提高頁(yè)面性能。

          const renderList = async () => {
              console.time('time')
              const list = await getList()
              console.log(list)
              const total = list.length
              const page = 0
              const limit = 200
              const totalPage = Math.ceil(total / limit)

              const render = (page) => {
                  if (page >= totalPage) return
                  requestAnimationFrame(() => {

                      const fragment = document.createDocumentFragment()
                      for (let i = page * limit; i < page * limit + limit; i++) {
                          const item = list[i]
                          const div = document.createElement('div')
                          div.className = 'sunshine'
                          div.innerHTML = `<img src="${item.src}" /><span>${item.text}</span>`

                          fragment.appendChild(div)
                      }
                      container.appendChild(fragment)
                      render(page + 1)
                  })
              }
              render(page)
              console.timeEnd('time')
          }

          延遲加載

          雖然后端一次返回這么多數(shù)據(jù),但用戶的屏幕只能同時(shí)顯示有限的數(shù)據(jù)。所以我們可以采用延遲加載的策略,根據(jù)用戶的滾動(dòng)位置動(dòng)態(tài)渲染數(shù)據(jù)。

          要獲取用戶的滾動(dòng)位置,我們可以在列表末尾添加一個(gè)空節(jié)點(diǎn)空白。每當(dāng)視口出現(xiàn)空白時(shí),就意味著用戶已經(jīng)滾動(dòng)到網(wǎng)頁(yè)底部,這意味著我們需要繼續(xù)渲染數(shù)據(jù)。

          同時(shí),我們可以使用getBoundingClientRect來(lái)判斷空白是否在頁(yè)面底部。

          使用 Vue 的示例代碼:


          <script setup lang="ts">
          import { onMounted, ref, computed } from 'vue'
          const getList = () => {
            // code as before
          }
          const container = ref<HTMLElement>() // container element
          const blank = ref<HTMLElement>() // blank element
          const list = ref<any>([])
          const page = ref(1)
          const limit = 200
          const maxPage = computed(() => Math.ceil(list.value.length / limit))
          // List of real presentations
          const showList = computed(() => list.value.slice(0, page.value * limit))
          const handleScroll = () => {
            if (page.value > maxPage.value) return
            const clientHeight = container.value?.clientHeight
            const blankTop = blank.value?.getBoundingClientRect().top
            if (clientHeight === blankTop) {
              // When the blank node appears in the viewport, the current page number is incremented by 1
              page.value++
            }
          }
          onMounted(async () => {
            const res = await getList()
            list.value = res
          })
          </script>

          <template>
            <div id="container" @scroll="handleScroll" ref="container">
              <div class="sunshine" v-for="(item) in showList" :key="item.tid">
                <img :src="item.src" /
          >
                <span>{{ item.text }}</span>
              </div>
              <div ref="blank"></
          div>
            </div>
          </
          template>

          最后

          我們從一個(gè)面試問(wèn)題開(kāi)始,討論了幾種不同的性能優(yōu)化技術(shù)。

          如果你在面試中被問(wèn)到這個(gè)問(wèn)題,你可以用今天的內(nèi)容回答這個(gè)問(wèn)題,如果你在工作中遇到這個(gè)問(wèn)題,你應(yīng)該先揍那個(gè)寫(xiě) API 的人。

          ////// END //////
          ↓ 點(diǎn)擊下方關(guān)注,看更多架構(gòu)分享 ↓
          瀏覽 89
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  特级西西高清4Www电影 | 久久成人免费网 | 大香蕉太香蕉成人现现 | 亚洲欧美国产精品久久久久久久 | 一级日逼 |