3

My goal is to show a log file in real time. I'm doing it through a websocket, but when the paragraph ('p') of the html starts to be big (450 lines), Chrome starts lagging and crashing.

The implementation is this:

var paragraph = document.getElementById('idLog');
stompClient.subscribe('/suscribers/tomcatlog', function (data) {
    var lineLog = JSON.parse(data.body);
    if (lineLog.line !== null) {
        paragraph.innerHTML += lineLog.line;
        paragraph.appendChild(document.createElement("br"));
        var elem = document.getElementById('main');
        elem.scrollTop = elem.scrollHeight;
    }
});

Why is this happening?

Peter B
  • 22,460
  • 5
  • 32
  • 69
un0tec
  • 170
  • 1
  • 11
  • 2
    I am not entirely sure on the exact cause of the issue here but why not just get a line, make it into a DOM element and append it to a list of others, instead of doing `+=` which is a heavy operation. – VLAZ Nov 21 '18 at 09:37

1 Answers1

1

Doing string manipulations using += with ever growing strings is notoriously slow. Each time the entire string has to be copied into a new one, with the new characters appended.

On top of that the ever growing string has to be parsed over and over again - after all we are running in a browser.

Instead you should create a Text Node and append it directly to the parent element, like this:

if (lineLog.line !== null) {
    paragraph.appendChild(document.createTextNode(lineLog.line));
    paragraph.appendChild(document.createElement("br"));
    // ...
}
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • I've changed the way to implement it as you say and it seems to work correctly. About 15 thousand log lines written correctly and no lagging in browser. Thank you very much for your help. – un0tec Nov 21 '18 at 10:25