Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
59
rated 0 times [  62] [ 3]  / answers: 1 / hits: 43800  / 15 Years ago, mon, september 7, 2009, 12:00:00

I have an HTML page that uses AJAX to retrieve messages from a server. I'm appending these messages to a as they are retrieved by setting its innerHTML property.



This works fine while the amount of text is small, but as it grows it causes Firefox to use all available CPU and the messages slow down to a crawl. I can't use a textbox, because I want some of the text to be highlighted in colour or using other HTML formatting. Is there any faster way to do this that wouldn't cause the browser to lock up?



I've tried using jQuery as well, but from what I've read setting .innerHTML is faster than its .html() function and that seems to be the case in my own experience, too.



Edit: Perceived performance is not an issue - messages are already being written as they are returned (using Comet). The issue is that the browser starts locking up. The amount of content isn't that huge - 400-500 lines seems to do it. There are no divs within that div. The entire thing is inside a table, but hopefully that shouldn't matter.


More From » html

 Answers
10

You specifically said that you were appending meaning that you are attaching it to the same parent. Are you doing something like:



myElem.innerHTML += newMessage;


or



myElem.innerHTML = myElem.innerHTML + newMessage;


because this is extremely inefficient (see this benchmark: http://jsben.ch/#/Nly0s). It would cause the browser to first do a very very large string concat (which is never good) but then even worse would have to re-parse insert and render everything you had previously appended. Much better than this would be to create a new div object, use innerHTML to put in the message and then call the dom method appendChild to insert the newly created div with the message. Then the browser will only have to insert and render the new message.


[#98745] Wednesday, September 2, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hector

Total Points: 726
Total Questions: 103
Total Answers: 100

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;