<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)該如何處理?

          共 13890字,需瀏覽 28分鐘

           ·

          2022-06-20 23:45

          最近,我的一位朋友在面試時(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 的人。

          原文:https://medium.com/frontend-canteen/if-the-backend-api-returns-100-000-records-at-one-time-how-should-we-handle-it-in-the-frontend-fab21218fe2

          我們創(chuàng)建了一個(gè)高質(zhì)量的技術(shù)交流群,與優(yōu)秀的人在一起,自己也會(huì)優(yōu)秀起來(lái),趕緊點(diǎn)擊加群,享受一起成長(zhǎng)的快樂(lè)。另外,如果你最近想跳槽的話,年前我花了2周時(shí)間收集了一波大廠面經(jīng),節(jié)后準(zhǔn)備跳槽的可以點(diǎn)擊這里領(lǐng)取

          推薦閱讀

          ··································

          你好,我是程序猿DD,10年開(kāi)發(fā)老司機(jī)、阿里云MVP、騰訊云TVP、出過(guò)書(shū)創(chuàng)過(guò)業(yè)、國(guó)企4年互聯(lián)網(wǎng)6年從普通開(kāi)發(fā)到架構(gòu)師、再到合伙人。一路過(guò)來(lái),給我最深的感受就是一定要不斷學(xué)習(xí)并關(guān)注前沿。只要你能堅(jiān)持下來(lái),多思考、少抱怨、勤動(dòng)手,就很容易實(shí)現(xiàn)彎道超車!所以,不要問(wèn)我現(xiàn)在干什么是否來(lái)得及。如果你看好一個(gè)事情,一定是堅(jiān)持了才能看到希望,而不是看到希望才去堅(jiān)持。相信我,只要堅(jiān)持下來(lái),你一定比現(xiàn)在更好!如果你還沒(méi)什么方向,可以先關(guān)注我,這里會(huì)經(jīng)常分享一些前沿資訊,幫你積累彎道超車的資本。

          點(diǎn)擊領(lǐng)取2022最新10000T學(xué)習(xí)資料


          瀏覽 45
          點(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>
                  国产精品第一页在线观看 | 射逼网| 91在线无码精品蜜桃 | 中文字幕第2页在线观看 | 亚洲免费无 |