I’d like to find a better way to output console messages to an HTML page. This method seems to be pretty slow.
<html> <title>Logging test</title> <head> <SCRIPT LANGUAGE='JavaScript' TYPE='text/javascript'> <!-- function log(s) { if(!log.start) { var date = new Date(); log.count = 0; _log('0', 'log() started at ' + date); log.start = date.valueOf(); } _log(new Date().valueOf() - log.start, s); } function _log(header, s) { var logMessages = document.getElementById('logMessages'); if(!logMessages) { alert(logMessages); return; } var message = document.createElement('div'); message.className = 'logMessage'; var content = ''; content += '<span class=\'time\'>' + header + '</span>'; content += '<span class=\'line\'>' + (log.count++) + '</span>'; content += '<span class=\'level\'>' + '' + '</span>'; content += '<span class=\'msg\'>' + s.replace(/ /g, ' ').replace(/\n/g, '<BR />') + '</span>'; message.innerHTML = content; logMessages.appendChild(message); setTimeout(function(){message.scrollIntoView(true)},1); } function main(e) { if(window.confirm('Would you like to display logging?')) { for(var i=0;i<5000;i++) { log('Hello World ' + i); } } } //--> </SCRIPT> <style> .logMessage { border-bottom: 1px black solid; font-size: 8pt; font-family: Lucida Console; } .logMessage .line, .logMessage .time { width: 30px; } .logMessage .level { display: none; } .logMessage .msg { } #logMessages { overflow: auto; } </style> </head> <body onload='main()'> <div id='logMessages'></div> </body> </html>
What’s the use case here? For debugging, Firebug’s console.log is all I can ever imagine needing. For your specific case, if you really want it to go to on the page and find your current solution to be too slow, I would definitely replace all the string concatenations with something a little more efficient (pushing strings into an array and joining them at the end, or a StringBuffer that abstracts it out), as string manipulation in Javascript is infamously bad in some browsers (I’m looking at you, Redmond!)