用javascript创建和附加一个大DOM - 最优化的方式?

时间:2010-05-20 18:27:13

标签: javascript jquery dom

我使用以下代码在移动浏览器(webkit)上附加一个大dom:

1. while(i--)  // 'i' ranges from 10 to possibly 1000
2. {
3.   var html01 = ['<div class="test">', someVal[i],'</div>',
4.                 '<div><p>', someTxt.txt1, anotherVal.val[i], '</p></div>',
5.   // lots of html snippets interspersed with variables that differ in each loop iteration
6.                  // on average ~40 to 50 elements in this array
7.                ].join('');
8.   var fragment = document.createDocumentFragment(),
9.   div = fragment.appendChild(document.createElement('div'));
10.  div.appendChild(jQuery(html01)[0]);
11.  someArray[someArray.length] = fragment;
12. } //end while loop
13. jQuery('#screen1').append(someArray);
14. // similarly i create 'html02' till 'html15' to append in other screen divs

有没有更好或更快的方法来做到这一点?你看到代码有什么问题吗?我有点担心第10行我在jquery中包装然后将其取出。

2 个答案:

答案 0 :(得分:2)

更新解决了追加唯一值的需求


我不是DOM API专家,但是这将创建您需要的元素,在循环中克隆它们,更新它们的textNode值,将它们附加到片段,然后将片段附加到DOM。

只要为文本节点提供的变量是正确的,它就会起作用。

    // Form a single fragment outside the loop
       var fragment = document.createDocumentFragment();

    // Create the first div and append a textNode
        var div1 = document.createElement('div');
        div1.appendChild( document.createTextNode('content') );
        div1.setAttribute('class','test');

    // Create the second div, its inner p element, and its textNode
        var div2 = document.createElement('div');
        var p = document.createElement('p');
        p.appendChild( document.createTextNode('content') );
        div2.appendChild( p );

    // Variables to store the clones of above
        var clone1, clone2;

    // Counter for while loop
        var i = 1000;

     while(i--)  // someIndex ranges from 10 to possibly 1000
     {
        // Clone the elements we created
        clone1 = div1.cloneNode(true);
        clone2 = div2.cloneNode(true);

        // Update the nodeValue of the first textNode in div1
        clone1.firstChild.nodeValue = 'someVal[i]';

        // Get the p element in div2 and update its nodeValue
        clone2.firstChild.firstChild.nodeValue = 'someTxt.txt1 + anotherVal.val[i]';

        // Append the elements we created, cloned and updated to the fragment
        fragment.appendChild(clone1).
        fragment.appendChild(clone2);
     }

        // Append the populated fragment to #screen1
     document.getElementById('screen1').appendChild(fragment);

修改

如果你想在追加它之前使用jQuery操作完成的片段,你需要这样做:

$(fragment.childNodes);  // Create a jQuery object of the content of the fragment

因为正常工作:

$(fragment);   // Doesn't work. jQuery methods will be ineffective.    

答案 1 :(得分:1)

为什么要包装jQuery?我认为没有任何好处,因为你可以放弃它而不需要额外的代码。

第10行 从

div.appendChild(jQuery(html01)[0]);

div.innerHTML = html01;

第13行 从

jQuery('#screen1').append(fragment);

document.getElementById("screen1").appendChild(fragment);

增益可能不会很大,但它会在那里。 除此之外(并根据显示的代码),我认为没有办法让事情变得更快。