Reputation: 1955
I have a class called render. That gets continually updated, and I would like to not update the whole class each time.
I have a string
var html1 = "<h1>Header</h1><p>this is a small paragraph</p><ul><li>list element 1.</li><li>list element 2.</li><li>list element 3.</li></ul>"
and $('.render').html(html1)
produces:
<div class="render">
<h1>Header</h1>
<p>this is a small paragraph</p>
<ul>
<li>list element 1.</li>
<li>list element 2.</li>
<li>list element 3.</li>
</ul>
</div>
Lets say that I get a new html string which is just an update of html1
var html2 =
"<h1>Header</h1>
<p>this is a small paragraph</p>
<ul>
<li>list element 1.</li>
<li>list element 2.</li>
<li>list element 3. With a small update.</li>
</ul>"
// newlines thrown in for clarity.
Is there a good way for me to insert the new html without re-rendering the whole thing.
Here is my project to try solve this issue github/rontgen.js
Upvotes: 1
Views: 230
Reputation: 1955
Ok so a preliminary solution of mine is as follows, its like @dave's above, but I dont traverse the dom.
$(function(){
// Cache the jQuery selectors
var $editor = $("#editor");
var $render = $('.render');
$editor.focus();
var firstTime = true;
var cache = [''];
var i = 0;
var row_num = 1000;
for(i = 0; i < row_num; i++){
$render.append('<div id="node'+i+'"></div>')
}
$editor.keyup(function(){
var fresh = $editor.val().split('\n\n');
var i = 0;
for(i = 0; i < fresh.length; i++){
console.log(fresh[i]!==cache[i])
if(fresh[i]!==cache[i]){
$('#node'+i).html(marked(fresh[i]))
renderMathJax('node'+i)
}
}
var j;
for(j = fresh.length; j < row_num; j++){
$('#node'+j).empty()
}
cache = fresh;
});
});
var renderMathJax = function (el) {
MathJax.Hub.Queue(["Typeset",MathJax.Hub,el]);
}
Its performance is good because it only inserts and doesn't re-render, but still a few oddities if I delete more than one line at a time.
Upvotes: 0
Reputation: 64677
Something like this should work (syntax may be off but this should give you an idea of how to do it)
$('.render').children().each(function() {
if ($(this).is('h1') && $(this).html() != html2.find('h1').html()) {
$(this).html(html2.find('h1').html());
}
else if ($(this).is('p') && $(this).html() != html2.find('p').html()) {
$(this).html(html2.find('p').html());
}
else if ($(this).is('ul') && $(this).html() != html2.find('ul').html()) {
for (i=0; i<$(this).children('li').length; i++) {
if ($(this).children('li')[i] != html2.find('ul').children('li')[i]) {
$(this).children('li')[i].html(html2.find('ul').children('li')[i].html());
}
}
}
});
Upvotes: 2