A long time ago, there was an interview to ask how to optimize the long list. At that time, I felt that the general front end would not have this function, and there were pagination, so I did not pay attention to it. Today we share an optimization method for long list rendering, shard loading, which is almost never used anymore, but it’s important to know.
Eventloop is a single thread. When you run the first main thread, you will put the macro task in the macro task queue and the micro task in the micro task queue. When the main thread is finished, the micro task queue will be emptied and the GUI will render the page. Then go to the macro task queue to extract the macro task from the main thread to execute, always loop.
To be clear, the page renders after the microtask has been emptied:
<ul id="wrap"></ul>
<script>
let time;
Promise.resolve().then(res => {
for (let i = 0; i < 10000000000; i++) {}
console.log('Microtask completed', new Date() - time); }) document.getelementById ('wrap').innerHTML = 'Page rendered';
time = new Date();
console.log('Page render statement Execution');
</script>
Copy the code
Then take a look at the rendering time and js execution time of 100,000 data pages:
<ul id="wrap"></ul>
<script>
let total = 100000;
let time = new Date();
for (let i = 0; i < total; i++) {
let li = document.createElement('li');
li.innerHTML = i;
document.getElementById('wrap').appendChild(li);
}
console.log('JS execution time', new Date() - time); // the js execution time is 710setTimeout(function () {
console.log('Page Render time', new Date() - time); }) </script>Copy the code
Js execution is fast, but page rendering takes nearly 5 seconds, compared to nearly a minute for a million data tests. So we’re going to slice render.
Fragment rendering:
<ul id="wrap"></ul>
<script>
let total = 100000;
let time = new Date();
let index = 0;
let id = 0;
function loadList() {
index += 50;
if(index < total){
setTimeout(function () {
for (let i = 0; i < 50; i++) {
let li = document.createElement('li');
li.innerHTML = id++;
document.getElementById('wrap').appendChild(li);
}
loadList();
})
}
}
loadList()
</script>
Copy the code
Shard rendering takes longer than no shard rendering, and the advantage is that you don’t have to wait for everything to render, you can see the data directly, and you can drag the scroll bar and see that the page is still loading.
One thing to note here is that the new version of the browser has been optimized for page rendering. It will update the page once after js execution is complete, instead of inserting one page after another during the for loop. If it is compatible with IE, it will render with document fragments. You can also use a macro task, requestAnimationFrame, instead of a timer for slightly better performance.
Although fragmentation rendering can be optimized, this method is still too many pages dom, so this method is almost not used now, the virtual list method is used to optimize.