Ci sono due metodi per aggiungere codice HTML al DOM e non so qual è il modo migliore per farlo.Dovresti aggiungere HTML al DOM usando innerHTML o creando nuovi elementi uno per uno?
Primo metodo
Il primo modo è quello semplice, si potrebbe semplicemente aggiungere codice HTML (con jQuery) utilizzando $('[code here]').appendTo(element);
che è molto simile element.innerHTML = [code here];
Secondo metodo
un altro modo è quello di creare tutti gli elementi uno ad uno come:
// New div-element
var div = $('<div/>', {
id: 'someID',
class: 'someClassname'
});
// New p-element that appends to the previous div-element
$('<p/>', {
class: 'anotherClassname',
text: 'Some textnode',
}).appendTo(div);
Questo metodo utilizza le funzioni di base come document.createElement
e element.setAttribute
.
Quando devo utilizzare il primo metodo e quando il secondo? Il metodo è più veloce del metodo uno?
Edit - Risultato della speed tests
ho fatto tre prove di velocità da cui il codice seguente:
$(document).ready(function(){
// jQuery method - Above mentioned as the second method
$('#test_one').click(function(){
startTimer();
var inhere = $('#inhere');
for(i=0; i<1000; i++){
$(inhere).append($('<p/>', {'class': 'anotherClassname' + i, text: 'number' + i}));
}
endTimer();
return false;
});
// I thought this was much like the jQuery method, but it was not, as mentioned in the comments
$('#test_two').click(function(){
startTimer();
var inhere = document.getElementById('inhere');
for(i=0; i<1000; i++){
var el = document.createElement('p')
el.setAttribute('class', 'anotherClassname' + i);
el.appendChild(document.createTextNode('number' + i));
inhere.appendChild(el);
}
endTimer();
return false;
});
// This is the innerHTML method
$('#test_three').click(function(){
startTimer();
var inhere = document.getElementById('inhere'), el;
for(i=0; i<1000; i++){
el += '<p class="anotherClassname' + i + '">number' + i + '</p>';
}
inhere.innerHTML = el;
endTimer();
return false;
});
});
che ha dato i seguenti risultati davvero sorprendenti
Test One Test Two Test Three
+-------------+---------+----------+------------+
| Chrome 5 | ~125ms | ~10ms | ~15ms |
| Firefox 3.6 | ~365ms | ~35ms | ~23ms |
| IE 8 | ~828ms | ~125ms | ~15ms |
+-------------+---------+----------+------------+
Tutto sommato il metodo innerHTML sembra essere il più veloce ed è in molti casi il più leggibile.
La velocità non è l'unica preoccupazione ... spesso, il codice scritto come il 'primo metodo' sarà infinitamente più leggibile rispetto al 'secondo metodo. –