admin管理员组文章数量:1129098
Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of:
$("<div></div>");
However, I'm getting the feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective?
This answer has the benchmarks to the suggestions below.
Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of:
$("<div></div>");
However, I'm getting the feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective?
This answer has the benchmarks to the suggestions below.
Share Improve this question edited May 23, 2017 at 12:10 CommunityBot 11 silver badge asked Nov 29, 2008 at 2:15 DarkoDarko 38.8k15 gold badges83 silver badges107 bronze badges 9- 1 Experiment with removing styles too and see if that speeds things up. I find CSS application and updates slow things down the most on big pages for me. – CVertex Commented Nov 29, 2008 at 5:00
- 3 Beware of premature optimization -- if you're not doing this for hundreds of DOM elements at a time, or using VERY old browsers, then you're probably not going to notice any difference in the browser's performance. – Blazemonger Commented Jul 31, 2012 at 21:43
- 1 @Blazemonger It wasn't so much that I needed a more efficient method of creating DOM elements, but the situation that I was in made me ponder what the alternatives are and how efficient they might be. – Darko Commented Aug 1, 2012 at 4:27
- 2 jQuery is a library – you will almost always incur overhead performance costs for this reason: it's like talking to someone through an interpreter. Unless you want to use raw JavaScript, take advantage of how quick it is to write $('<div>') and accept the performance hit. – Danny Bullis Commented Apr 15, 2013 at 2:44
- 1 jsben.ch/#/bgvCV <= this benchmark should answer your question – EscapeNetscape Commented Nov 7, 2016 at 12:58
12 Answers
Reset to default 312I use $(document.createElement('div'));
Benchmarking shows this technique is the fastest. I speculate this is because jQuery doesn't have to identify it as an element and create the element itself.
You should really run benchmarks with different Javascript engines and weigh your audience with the results. Make a decision from there.
personally i'd suggest (for readability):
$('<div>');
some numbers on the suggestions so far (safari 3.2.1 / mac os x):
var it = 50000;
var start = new Date().getTime();
for (i = 0; i < it; ++i) {
// test creation of an element
// see below statements
}
var end = new Date().getTime();
alert( end - start );
var e = $( document.createElement('div') ); // ~300ms
var e = $('<div>'); // ~3100ms
var e = $('<div></div>'); // ~3200ms
var e = $('<div/>'); // ~3500ms
Question:
What is the most efficient way to create HTML elements using jQuery?
Answer:
Since it's about jQuery
then I think it's better to use this (clean) approach (you are using)
$('<div/>', {
'id':'myDiv',
'class':'myClass',
'text':'Text Only',
}).on('click', function(){
alert(this.id); // myDiv
}).appendTo('body');
DEMO.
This way, you can even use event handlers for the specific element like
$('<div/>', {
'id':'myDiv',
'class':'myClass',
'style':'cursor:pointer;font-weight:bold;',
'html':'<span>For HTML</span>',
'click':function(){ alert(this.id) },
'mouseenter':function(){ $(this).css('color', 'red'); },
'mouseleave':function(){ $(this).css('color', 'black'); }
}).appendTo('body');
DEMO.
But when you are dealing with lots of dynamic elements, you should avoid adding event handlers
in particular element, instead, you should use a delegated event handler, like
$(document).on('click', '.myClass', function(){
alert(this.innerHTML);
});
var i=1;
for(;i<=200;i++){
$('<div/>', {
'class':'myClass',
'html':'<span>Element'+i+'</span>'
}).appendTo('body');
}
DEMO.
So, if you create and append hundreds of elements with same class, i.e. (myClass
) then less memory will be consumed for event handling, because only one handler will be there to do the job for all dynamically inserted elements.
Update : Since we can use following approach to create a dynamic element
$('<input/>', {
'type': 'Text',
'value':'Some Text',
'size': '30'
}).appendTo("body");
But the size
attribute can't be set using this approach using jQuery-1.8.0
or later and here is an old bug report, look at this example using jQuery-1.7.2
which shows that size
attribute is set to 30
using above example but using same approach we can't set size
attribute using jQuery-1.8.3
, here is a non-working fiddle. So, to set the size
attribute, we can use following approach
$('<input/>', {
'type': 'Text',
'value':'Some Text',
attr: { size: "30" }
}).appendTo("body");
Or this one
$('<input/>', {
'type': 'Text',
'value':'Some Text',
prop: { size: "30" }
}).appendTo("body");
We can pass attr/prop
as a child object but it works in jQuery-1.8.0 and later
versions check this example but it won't work in jQuery-1.7.2 or earlier
(not tested in all earlier versions).
BTW, taken from jQuery
bug report
There are several solutions. The first is to not use it at all, since it doesn't save you any space and this improves the clarity of the code:
They advised to use following approach (works in earlier ones as well, tested in 1.6.4
)
$('<input/>')
.attr( { type:'text', size:50, autofocus:1 } )
.val("Some text").appendTo("body");
So, it is better to use this approach, IMO. This update is made after I read/found this answer and in this answer shows that if you use 'Size'(capital S)
instead of 'size'
then it will just work fine, even in version-2.0.2
$('<input>', {
'type' : 'text',
'Size' : '50', // size won't work
'autofocus' : 'true'
}).appendTo('body');
Also read about prop, because there is a difference, Attributes vs. Properties
, it varies through versions.
Actually, if you're doing $('<div>')
, jQuery will also use document.createElement()
.
(Just take a look at line 117).
There is some function-call overhead, but unless performance is critical (you're creating hundreds [thousands] of elements), there isn't much reason to revert to plain DOM.
Just creating elements for a new webpage is probably a case in which you'll best stick to the jQuery way of doing things.
This is not the correct answer for the question but still I would like to share this...
Using just document.createElement('div')
and skipping JQuery will improve the performance a lot when you want to make lot of elements on the fly and append to DOM.
If you have a lot of HTML content (more than just a single div), you might consider building the HTML into the page within a hidden container, then updating it and making it visible when needed. This way, a large portion of your markup can be pre-parsed by the browser and avoid getting bogged down by JavaScript when called. Hope this helps!
I think you're using the best method, though you could optimize it to:
$("<div/>");
You don't need raw performance from an operation you will perform extremely infrequently from the point of view of the CPU.
You'll have to understand that the significance of element creation performance is irrelevant in the context of using jQuery in the first place.
Keep in mind, there's no real purpose of creating an element unless you're actually going to use it.
You may be tempted to performance test something like $(document.createElement('div'))
vs. $('<div>')
and get great performance gains from using $(document.createElement('div'))
but that's just an element that isn't in the DOM yet.
However, in the end of the day, you'll want to use the element anyway so the real test should include f.ex. .appendTo();
Let's see, if you test the following against each other:
var e = $(document.createElement('div')).appendTo('#target');
var e = $('<div>').appendTo('#target');
var e = $('<div></div>').appendTo('#target');
var e = $('<div/>').appendTo('#target');
You will notice the results will vary. Sometimes one way is better performing than the other. And this is only because the amount of background tasks on your computer change over time.
Test yourself here
So, in the end of the day, you do want to pick the smallest and most readable way of creating an element. That way, at least, your script files will be smallest possible. Probably a more significant factor on the performance point than the way of creating an element before you use it in the DOM.
Someone has already made a benchmark: jQuery document.createElement equivalent?
$(document.createElement('div'))
is the big winner.
One point is that it may be easier to do:
$("<div class=foo id=bar style='color:white;bgcolor:blue;font-size:12pt'></div>")
Then to do all of that with jquery calls.
I am using jquery.min v2.0.3 . It's for me better to use following:
var select = jQuery("#selecter");
jQuery("`<option/>`",{value: someValue, text: someText}).appendTo(select);
as following:
var select = jQuery("#selecter");
jQuery(document.createElement('option')).prop({value: someValue, text: someText}).appendTo(select);
Processing time of first code is much lower than second code.
本文标签: javascriptWhat is the most efficient way to create HTML elements using jQueryStack Overflow
版权声明:本文标题:javascript - What is the most efficient way to create HTML elements using jQuery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736697961a1948282.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论