开发者

$('<div>', {id: 'bla'}) versus $('<div id="bla"></div>);

I开发者_Python百科s there any difference in speed between:

$('<div>', {id: 'bla', click: func, css: { opacity:0.5 } }

and doing it all inline?

$('<div id="bla" style="opacity:0.5"></div>').click(func);

What does jquery do internally for the second example? Just call .innerHTML or does it try to parse it and then do it exactly the same was as the first example?


When we pass html markup as an input to $() it uses document.createDocumentFragment to create the elements on the fly and then uses childnodes property to retrieve the actual elements and performs the required operation.


The best way to decide if one snippet is better than the other is to benchmark them yourself.

You can use jsPerf.com to benchmark your code.

Turns out the second version is faster in Firefox and they are about the same on Chrome.

http://jsperf.com/test-jquery-element-creator

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜