[心得] Expand Your Options in a SELECT Element
FROM: http://msdn.microsoft.com/library/default.asp?url=/workshop/author/perf/dhtmlperf.asp
An exception to our earlier rule about using the HTML text methods is when you add a large number of OPTION elements to a SELECT element. It is more efficient to use the innerHTML property than to call the createElement method to access the options collection.
Tip 5: Use innerHTML to add a large number of options to a SELECT element.
Use string concatenation to build up the SELECT element HTML text, then use this to set the innerHTML property. For very large numbers of options, string concatenation can also affect performance. In this situation, build an array and call the Microsoft JScript join method to perform a final concatenation of the OPTION element HTML text.
Show Me
Slow:
var opt;
divUpdate.innerHTML = "<SELECT ID='selUpdate'></SELECT>";
for (var i=0; i<1000; i++)
{
opt = document.createElement( "OPTION" );
selUpdate.options.add( opt );
opt.innerText = "Item " + i;
}
Fast:
var str="<SELECT ID='selUpdate'>";
for (var i=0; i<1000; i++)
{
str += "<OPTION>Item " + i + "</OPTION>";
}
str += "</SELECT>";
divUpdate.innerHTML = str;
Faster:
var arr = new Array(1000);
for (var i=0; i<1000; i++)
{
arr[i] = "<OPTION>Item " + i + "</OPTION>";
}
divUpdate.innerHTML = "<SELECT ID='selUpdate'>" + arr.join() + "</SELECT>";
--
唐 李商隱 無題
相見時難別亦難,東風無力百花殘。春蠶到死絲方盡,蠟炬成灰淚始乾。
曉鏡但愁雲鬢改,夜吟應覺月光寒。蓬山此去無多路,青鳥殷勤為探看。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 125.229.164.118
→
11/21 11:49, , 1F
11/21 11:49, 1F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):