2010-02-23 11 views
17

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.

risposta

2

Indico un obsoleto article per scopi di persone prove per se stessi. I metodi DOM effettivamente battono il innerHTML su tutte le mie macchine, quindi è quello che preferisco. Tuttavia, al momento dell'articolo innerHTML era più veloce in avg. Attualmente la differenza può essere vista solo in enormi set di dati drasticamente.

+1

La velocità non è l'unica preoccupazione ... spesso, il codice scritto come il 'primo metodo' sarà infinitamente più leggibile rispetto al 'secondo metodo. –

0

Se ho intenzione di riutilizzare il div più avanti nel codice, lo costruirò e lo inserirò in una var, ussually con un prefisso $ così so che si tratta di un oggetto jquery. Se si tratta di una cosa una tantum mi limiterò a fare un:

$('body').append(the stuff) 
2

In realtà, né metodi utilizzano innerHTML, in entrambi i casi jQuery converte il codice HTML di nodi DOM. Da jquery-1.3.2.js:

// If a single string is passed in and it's a single tag 
// just do a createElement and skip the rest 
if (!fragment && elems.length === 1 && typeof elems[0] === "string") { 
    var match = /^<(\w+)\s*\/?>$/.exec(elems[0]); 
    if (match) 
     return [ context.createElement(match[1]) ]; 
} 

// ... some more code (shortened so nobody falls asleep) ... 

// Convert html string into DOM nodes 
if (typeof elem === "string") { 
    // Fix "XHTML"-style tags in all browsers 
    elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){ 
     return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ? 
      all : 
      front + "></" + tag + ">"; 
    }); 
    // etc... 
} 

In generale, usando innerHTML è più lento di manipolare il DOM, perché richiama il parser HTML (che analizzerà il codice HTML nel DOM comunque).

Problemi correlati