Realize the correct loading of text message

Amazing programmer 2021-02-23 03:43:19
realize correct loading text message


Preface

yesterday , In my open source project chat-system When viewing chat records in , If there is a picture in the message, the position of the scroll bar will be miscalculated , This leads to inaccurate positioning of the last message .

After some investigation , It finally solved the problem , This article will share with you my solutions and ideas , Welcome all interested developers to read this article .

Problem analysis

As shown in the figure below , Let's click to open a chat window , The last message is the picture , Error in scroll bar position calculation , There's no bottom , The picture is not completely displayed , When the history message is pulled up, it is also due to the error of scroll bar position calculation caused by the picture , Not correctly located to the last viewed message location .

Scroll bar bottoming analysis

Let's take a look at the implementation code of scroll bar position calculation when touching the bottom :

 nextTick().then(() => {
let scrollHeight = 0;
if (messagesContainer.value == null) return;
// Gets the height of the message container's scroll area 
scrollHeight = messagesContainer.value.scrollHeight;
// If the current scroll bar is at the bottom or the current message is sent by the sender, modify the position of the scroll bar 
if (isBottomOut.value || data.isSendMessages.value) {
// New message rendering complete , Change scroll bar position 
messagesContainer.value.scrollTop = scrollHeight;
}
});
 Copy code 

As shown in the above code , We are nextTick The height of the scrolling area of the message container is obtained in the callback , Then change the position of the scroll bar to the height of the scroll area , So the scroll bar hits the bottom , Logically, no problem , And it's normal in plain text messages .

that , The problem may be getting the height of the message container , Not getting the right , So I tried to scrollHeight Change it to 99999, So its scroll bar must be at the bottom .

However , It's not as smooth as I expected , Change to 99999 after , The scroll bar is still in the wrong position .

that , I think the problem should be nextTick() The back scroll bar is really at the bottom , But the picture hasn't been loaded yet , After the picture is loaded, the scroll bar position changes again .

here , We found the problem , Then we can get the following solution :

  • Get all the chat pictures in the page
  • Traversing the acquired image
  • After each image is loaded, the height of the scrollable container is obtained , Then change the scroll bar position

Scroll bar top analysis

When touching the top to load data , It's also because of the pictures , It leads to the calculation error of scroll bar position , At the beginning, I chose to follow the plan when it hit the bottom , etc. img Get the height of the scroll container after loading , Then use the current message container height - Last saved message container height , So you can calculate the position of the scroll bar when you last viewed the message .

According to the above ideas, after realizing , The scroll bar is still in the wrong position , After some debugging , I found that every time I hit the top ,dom Will reload , Naturally, images that have been loaded will be reloaded again , The location of the scroll bar is naturally wrong .

After some thinking , I came up with a solution , Since it won't work when the picture is loaded , I'll use the timer .

  • nextTick() after , wait for 150ms, Then get the scrollable height of the message container .
  • Calculate the position of the scroll bar
  • Change scroll bar position

Implementation code

Next , Let's take a look at the specific implementation code .

Scroll bar bottoms

Some of the codes when the scroll bar bottoms are as follows , Complete code, please move to :messageParsing.ts

 nextTick().then(() => {
const scrollHeight = 0;
// Get all the chat pictures in the page 
const previewablePanel = document.getElementsByClassName("previewable");
if (messagesContainer.value == null) return;
for (let i = 0; i < previewablePanel.length; i++) {
const item = previewablePanel.item(i) as HTMLImageElement;
item.onload = () => {
if (messagesContainer.value == null) return;
// Bottom scroll bar 
bottomScrollBar(
scrollHeight,
messagesContainer as Ref<HTMLDivElement>,
isBottomOut,
msgListPanelHeight,
isFirstLoading
);
};
}
});
 Copy code 
const bottomScrollBar = (
scrollHeight: number,
messagesContainer: Ref<HTMLDivElement>,
isBottomOut: Ref<boolean>,
msgListPanelHeight: Ref<number>,
isFirstLoading: Ref<boolean>
) => {
const data = initData();
// Display message content 
data.msgShowStatus.value = "";
// Get the container height 
scrollHeight = messagesContainer.value.scrollHeight;
// If the current scroll bar is at the bottom or the current message is sent by the sender, modify the position of the scroll bar 
if (isBottomOut.value || data.isSendMessages.value) {
// New message rendering complete , Change scroll bar position 
messagesContainer.value.scrollTop = scrollHeight;
// Update message record container height 
msgListPanelHeight.value = scrollHeight;
// Modify the first loading status of the component to false
isFirstLoading.value = false;
// Modify the message sender status to false
data.isSendMessages.value = false;
}
};
 Copy code 

The scroll bar hits the top

Some of the codes when the scroll bar reaches the top are as follows , Complete code, please move to :messageParsing.ts

 nextTick().then(() => {
// Hide message content 
data.msgShowStatus.value = "hidden";
if (data.pageNo.value > 20) {
// Data loading exceeds 20 strip , Load time changed to 400ms
loadingTime = 400;
}
setTimeout(() => {
if (messagesContainer.value == null) return;
scrollHeight = messagesContainer.value.scrollHeight;
// Loading history messages , Change scroll bar position : Current message record container height - Message record container height 
messagesContainer.value.scrollTop =
scrollHeight - msgListPanelHeight.value;
// A message rendering is complete , The total number of messages to be rendered is reduced by itself 
msgTotals.value--;
// Determine whether the message is rendered 
if (msgTotals.value === 0) {
// Display message content 
data.msgShowStatus.value = "";
// Turn off loading animation 
isLoading.value = false;
// Loading history message complete , Update message record container height 
msgListPanelHeight.value = scrollHeight;
}
}, loadingTime);
});
 Copy code 

In the above code , The time of the timer is dynamic , It's because I found that when the messages loaded exceed 20 When the page , wait for 150ms I can't get the correct height of the rolling container , Need to wait 400ms.

Realization effect

Next , Let's take a look at the final implementation .

The scroll bar hits the top

In the above implementation code , I also made an optimization ,nextTick And then I hid the message , After the scroll bar position calculation is completed , Let the content of the message be displayed again .

As for why we need to do this optimization , I passed gif Let's take a picture , Let's take a look at the top loading effect without optimization , As shown below :

As shown in the figure above , When the message is not optimized, the error location message will be flashed first , Then the right message will be displayed , It's hard to watch .

Next , Let's take a look at the optimized effect , As shown below :

After optimization , The visual effect is much better than when it is not optimized , Although there are still some flaws , It'll flash , No other solution can be thought of at the moment , This is the only way , If you have a better plan , You can discuss it together in the comments section .

Scroll bar bottoms

When the scroll bar bottoms , Because it is necessary to modify the position of the scroll bar after loading the picture , When the picture is not loaded , The interface will flash the message of the wrong location first , And then the right news .

At the bottom , I used the same solution as when I hit the top , After the scroll bar position is calculated, the chat record will be displayed , The effect is as follows :

Project address

At the end

  • Any errors in the text , Please correct in the comment area , If this article helps you , Welcome to praise and concern
  • This article starts with Nuggets , Reprint is prohibited without permission
版权声明
本文为[Amazing programmer]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210222134322220P.html

  1. Configure the certificate to enable ngnix to publish the trusted website of HTTPS
  2. Javascript数据类型
  3. HTTP interface debugging tool! 48000 star HTTP command line client!
  4. Parameter encryption of front end URL link band
  5. HTTP interface debugging tool! 48000 star HTTP command line client!
  6. Three front end frameworks: data binding and data flow
  7. Reading Axios source code (1) -- exploring the realization of basic ability
  8. Event bubble and capture in JavaScript
  9. 【微前端】微前端最終章-qiankun指南以及微前端整體探索
  10. R & D solution e-Car front end monitoring system
  11. [JS] 877 - 35 wonderful knowledge of JavaScript, long experience!
  12. R & D solution e-Car front end monitoring system
  13. High performance nginx HTTPS tuning - how to speed up HTTPS by 30%
  14. 解决ajax跨域问题【5种解决方案】
  15. Top ten classic sorting of JavaScript
  16. HTTP 1. X learning notes: an authoritative guide to Web Performance
  17. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control component
  18. My http / 1.1 is so slow!
  19. Why Vue uses asynchronous rendering
  20. The response status was 0. Check out the W3C XMLHttpRequest Level 2 spec for
  21. The tapable instance object hook of webpack4. X core tool library
  22. The tapable instance object hook of webpack4. X core tool library
  23. Using libcurl for HTTP communication in C + +
  24. Using libcurl for HTTP communication in C + +
  25. Using CSS variable in Vue
  26. Deeply understand the update of state and props in react
  27. No matter how fast the Internet is, it's useless! In addition to Baidu disk, there is this website slow to let you eat shriveled
  28. Baidu share does not support the solution of HTTPS
  29. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  30. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  31. Vue cli creates vue3 project
  32. Nginx reverse proxy for windows authentication using NTLM
  33. Rust tutorial: introduction to rust for JavaScript developers
  34. Deploying personal blog to Tencent cloud with serverless framework
  35. R & D solution e-Car front end monitoring system
  36. JavaScript advanced learning
  37. Spend 1 minute to master these 5 ppt tips, courseware making less detours
  38. Vue: vuex persistent state
  39. React native gets the current network state of the device Netinfo
  40. High performance nginx HTTPS tuning - how to speed up HTTPS by 30%
  41. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  42. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  43. Vue determines whether the El form in the elementui is updated or changed. If it changes, it will prompt whether to save it. If it does not change, it will leave directly
  44. Algorithm problem: sum of two numbers -- JavaScript and Java implementation
  45. High performance nginx HTTPS tuning
  46. JQuery advanced
  47. day 30 jQuery
  48. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  49. TCP/IP 开胃菜 之 HTTP
  50. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  51. JavaScript data type
  52. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  53. Solve Ajax cross domain problem [5 solutions]
  54. HTTP of TCP / IP appetizer
  55. Optimization of pod creation efficiency in serverless scenario
  56. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%
  57. First knowledge of HTTP / 1.1
  58. First knowledge of HTTP / 1.1
  59. Webpack learning notes series 05 devserver
  60. Webpack learning notes series 04 - resource processing optimization