In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how the web front end can better display the 100, 000 pieces of data returned by the back end". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how the web front end can better display the 100, 000 pieces of data returned by the back end.
Front work
The pre-work can be done before the test can be carried out.
Back-end building
Create a new server.js file, simply start a service, return 10w pieces of data to the front end, and start the service through nodemon server.js
Students who do not install nodemon can install npm i nodemon-g globally first.
/ / server.jsconst http = require ('http') const port = 8000 Http.createServer (function (req, res) {/ / enable Cors res.writeHead (200,{ / / set cross-domain domain names), or set * allow all domain names' Access-Control-Allow-Origin':'*', / / cross-domain allowed request method You can also set * allow all methods "Access-Control-Allow-Methods": "DELETE,PUT,POST,GET,OPTIONS", / / allowed header type 'Access-Control-Allow-Headers':' Content-Type'}) let list = [] let num = 0 / / list for that generates 100000 pieces of data (let I = 0 I
< 1000000; i++) { num++ list.push({ src: 'https://p3-passport.byteacctimg.com/img/user-avatar/d71c38d1682c543b33f8d716b3b734ca~300x300.image', text: `我是${num}号嘉宾林三心`, tid: num }) } res.end(JSON.stringify(list));}).listen(port, function () { console.log('server is listening on port ' + port);})前端页面 先新建一个 index.html // index.html// 样式 * { padding: 0; margin: 0; } #container { height: 100vh; overflow: auto; } .sunshine { display: flex; padding: 10px; } img { width: 150px; height: 150px; } // html部分 然后新建一个 index.js 文件,封装一个 AJAX 函数,用来请求这 10w 条数据 // index.js // 请求函数const getList = () =>{return new Promise ((resolve, reject) = > {/ / step 1: create asynchronous object var ajax = new XMLHttpRequest (); / / step 2: set the url parameter of the request. Parameter 1 is the type of the request, and parameter 2 is the url of the request. You can take the parameter ajax.open ('get',' http://127.0.0.1:8000');). / / step 3: send the request ajax.send () / / step 4: register the event onreadystatechange status change and call ajax.onreadystatechange = function () {if (ajax.readyState = = 4 & & ajax.status = = 200) {/ / step 5. If you can get into this judgment, the data will come back perfectly. And the requested page is the existing resolve (JSON.parse (ajax.responseText)})} / / get the container object const container = document.getElementById ('container') render directly
The most direct way is to render it directly, but this is definitely not desirable, because rendering 10w nodes at a time is very time-consuming. We can take a look at it. It takes about 12 seconds, which is very time-consuming.
Const renderList = async () = > {console.time ('list time') const list = await getList () list.forEach (item = > {const div = document.createElement ('div') div.className =' sunshine' div [XSS _ clean] = `
${item.text} `container.appendChild (div)}) console.timeEnd ('list time')} renderList () setTimeout paging rendering
This method is to divide 10w limit into a total of Math.ceil (total / limit) pages according to the number of pages, and then use setTimeout to render one page of data at a time, so that the time to render the home page data is greatly reduced.
Const renderList = async () = > {console.time ('list time') const list = await getList () console.log (list) const total = list.length const page = 0const limit = 200const 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[xss_clean] = `${item.text} `container.appendChild (div)} render (page + 1)}, 0)} render (page) console.timeEnd ('list time')} requestAnimationFrame
Using requestAnimationFrame instead of setTimeout reduces the number of rearrangements and greatly improves performance. It is recommended that you use requestAnimationFrame more in rendering.
Const renderList = async () = > {console.time ('list time') const list = await getList () console.log (list) const total = list.length const page = 0const limit = 200const totalPage = Math.ceil (total / limit) const render = (page) = > {if (page > = totalPage) return / / use requestAnimationFrame instead of setTimeout requestAnimationFrame (() = > {for (let I = page * limit; I)
< page * limit + limit; i++) { const item = list[i] const div = document.createElement('div') div.className = 'sunshine' div[xss_clean] = `${item.text} `container.appendChild (div)} render (page + 1)}, 0)} render (page) console.timeEnd ('list time')} document fragments + requestAnimationFrame
Benefits of document fragmentation
1. In the past, we used to appendChild every time a div tag was created, but if there is a document fragment, you can first put the 1-page div tag into the document fragment, and then appendChild it to the container at one time, which reduces the number of appendChild and greatly improves the performance.
2. The page will only render the elements wrapped in the document fragments, not the document fragments
Const renderList = async () = > {console.time ('list time') const list = await getList () console.log (list) const total = list.length const page = 0const limit = 200const totalPage = Math.ceil (total / limit) const render = (page) = > {if (page > = totalPage) return requestAnimationFrame () = > {/ / create a document fragment 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[xss_clean] = `${item.text} `/ / insert document fragments fragment.appendChild (div)} / / one-time appendChild container.appendChild (fragment) render (page + 1)}, 0)} render (page) console.timeEnd ('list time')} lazy load
For a more popular explanation, let's start a vue front-end project, and the back-end service is still open
In fact, the principle of implementation is very simple, we show it through a diagram, that is, put an empty node blank at the end of the list, then render the data on page 1 first, scroll up, wait until blank appears in the view, and then load the second page, and so on.
As for how to determine that blank appears on the view, you can use the getBoundingClientRect method to get the top property
Import {onMounted, ref Computed} from 'vue'const getList = () = > {/ / same code as above} const container = ref () / / container node const blank = ref () / / blank node const list = ref ([]) / / list const page = ref (1) / / current number of pages const limit = 200 / / one page display / / maximum number of pages const maxPage = computed (() = > Math.ceil (list.value.length / limit)) / / Real list const showList = computed (()) = > list.value.slice (0) Page.value * limit) const handleScroll = () = > {/ / comparison of the current number of pages with the maximum number of pages if (page.value > maxPage.value) return const clientHeight = container.value?.clientHeight const blankTop = blank.value?.getBoundingClientRect () .top if (clientHeight = blankTop) {/ / blank appears in the view Then the current number of pages plus 1 page.value++}} onMounted (async () = > {const res = await getList () list.value = res})
{{item.text}} at this point, I believe you have a deeper understanding of "how the web front end can better display the 100, 000 pieces of data returned by the back end". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.