Which is better to use and why?
if ($(target).parents('div#test').length) {
or
var target = $(evt.target);
if (target.parents('div#test').length){
There are preformance gains to be had in using the second option. If you are going to reuse the selector multiple times.
Essentially you are caching your DOM traversal if you use the same selector multiple times.
See this answer for more details
Related
I have a very big single html page. I am performing data manipulation to that page. I am wondering if there is any best way for Jquery selector.
like
$("#id").text("ABC");
Above statement searches for tags in my HTML page, since my HTML is very big. is there any performance tip for that ?
for ex:
Which one is faster ?
$(document).on("click", "#contactsTab", callback);
or
$("#contactsTab").on("click", callback);
If you're going to re-use $("#id"), I would store it in a variable and then use that. Otherwise, you're searching through the DOM each time for that element.
var $element = $("#id");
$element.text("ABC");
Searching by id is the fastest dom search. It might be nominally faster to do:
document.getElementById("id").innerHTML = "ABC";
An ID selector should have the most optimal of all jQuery selector performances.
Ideally you should not have more than one element on the page having that id.
Whenever I want to find if an element exist in the DOM I use the following code.
if($('#target').length){
// do stuff.
}
This works well and I use it quite a lot on client sites.
Question:
How fast is this method? What are the speed implications when this is used a lot in a project?
You would be much better off using if(document.getElementById('target')) instead. JavaScript is always faster than jQuery (since jQuery is just a bunch of JavaScript hidden under the carpet)
EDIT: If you use it a lot, you can make a custom function:
function idExists(id) {return !!document.getElementById(id);}
Native JS is always faster than a query through jQuery. It just may not be as friendly.
After running a query through jsperf.com, native (querySelectorAll) is 57% faster than jQuery
However, if you use id, jQuery will be faster than querySelectorAll. In any case of id, use document.getElementById to test for an elements existence.
http://jsperf.com/jquery-obj-length
Try searching a DOM element with JQuery context say:
if an element u search say, an Input control, lies with in a table, pass table as your context:
A simple example:
$(function(){
var name= $('#Name','#mytab').val();
alert(name);
});
the jquery engine find the element 'Name' with in 'mytab' and not the entire form
follow this fiddle link : http://jsfiddle.net/NzbJr/10/
I need to retrieve the first element.
I do that with this code...
$(element).find('.x').first();
As much as I understand, that code...
Retrieves all elements from element that matched .x,
Removes unneeded elements;
Is there any better way to do it? Like $.findOne() or something?
As per jQuery docs:
Because :first is a jQuery extension and not part of the CSS
specification, queries using :first cannot take advantage of the
performance boost provided by the native DOM querySelectorAll()
method. To achieve the best performance when using :first to select
elements, first select the elements using a pure CSS selector, then
use .filter(":first").
So rewriting your selector to:
$(element).find('.x').filter(":first")
or (this one will give you direct descendants only and will be faster than .find, unless you're looking for nested elements too)
$(element).children('.x').filter(":first")
should give you better results.
Update After valuable inputs from kingjiv and patrick dw (see comments),
it does seem that these two are faster than .filter(':first') contrary to what the doc claims.
$(element).find('.x').first(); // faster
$($(element).find('.x')[0]); // fastest
If you want to have it real fast, you should use native browsers methods. Modern browsers support querySelector [docs]:
var $result;
if(element.querySelector) {
$result = $(element.querySelector('.x'));
}
else {
$result = $(element).find('.x').first();
}
The usage is a bit limited, as it would only work if element is a single element and if the selector is a valid CSS selector. You could make a plugin out of it. But then, if you consider all cases, like multiple elements etc., there is probably no advantage anymore.
So again, if you have a very specific use case, this might be useful, if not, stick with jQuery.
Update: Turns out, making a plugin is still faster: jsPerf benchmark
(function($) {
$.fn.findOne = function(selector) {
try {
var element, i = 0, l = this.length;
while(i < l && (element = this[i].querySelector(selector)) === null) {
i++;
}
return $(element);
}
catch(e) {
return this.find(selector).first();
}
};
}(jQuery));
How this works:
The plugin iterates over the selected DOM elements and calls querySelector on each of them. Once an element is found, the loop will terminate and return the found element. There are two reasons an exception could occur:
The browsers does not support querySelector
The selector is not a pure CSS selector
In both cases the plugin will fall back to use the normal jQuery method.
As crazy as it seems, in every performance test I've seen, .first() has better performance than :first.
As most people are suggesting, it seems as though using $(element).find(".x:first") should have better performance. However, in reality .first is faster. I have not looked into the internals of jquery to figure out why.
http://jsperf.com/jquery-select-first
And apparently using [0] and then rewrapping in a jquery object is the fastest:
$($(element).find(".x")[0])
EDIT: See mrchief's answer for an explanation of why. Apparently they have now added it to the documentation.
This should be better
$(element).find('.x:first');
Use :first selector:
$(element).find('.x:first')
It's better to write:
$('a:first');
What you're writing is "in 'element', find '.x' and return the first one". And that can be expressed like this
$('.x:first', element);
how about using first-child pseudo class ? like
$(element).find('.x:first-child')
However it might generate issues if your structure is like
<div>
<p></p>
</div>
<div>
<p></p>
</div>
so actually it is not what you are looking for (if you mean general solution). Others mnetions :first and this seems to be the correct approach
Your bottleneck is really the .find(), which searches all the descendants instead of just the immediate children.
On top of that, you're searching for a class .x (which uses a jQuery custom search) instead of an ID or a tagname (which use native DOM methods).
I would use Mrchief's answer and then, if possible, fix those two bottlenecks to speed up your selector.
You could combine the $(element) and .find() calls using a descendant selector; I'm unsure of the performance comparison:
$("#element .x").first().hide();
That way is fine according to the jQuery documentation, or at least better than using :first selector.
You can try as alternatives .filter(":first") or get the first element using array accessor against the .find() result [0].
Also, instead of .find() you can change it to:
$('.x', element)
To narrow the search to .x elements inside element, intead of searching the whole document.
Can I determine the number of jQuery objects on a page?
I want to use the number of elements as a sort of weak benchmark for page complexity. I'm thinking that if I can reduce the number of elements that jQuery knows about , the page might run more efficiently.
Does this make sense?
Is it as simple as doing a * select and counting the results?
related:
How can I clear content without getting the dreaded “stop running this script?” dialog?
http://api.jquery.com/size/
var elementCount = $('*').size();
Although this might be more what you want:
var elementCount = $('body').find('*').size()
var n= 0;
for (var i in jQuery.cache)
n++;
Now n holds the number of elements jQuery has ‘touched’ (added data to, such as event handlers).
Previously this used to be a whole lot, as it would ‘touch’ every element it was even checking for data. This unpleasantness is fixed in jQuery 1.4.
As for clearing content, yes, you can use innerHTML= '' to remove all the content without giving jQuery the chance to detach its data so very slowly. If you know there are no ‘touched’ elements inside the element that's a win, but otherwise it's a potential memory leak until the page is reloaded, as unused jQuery.cache data stays around.
Using live()/delegate() event binding avoids adding data to its target elements, which can allow you to use this short-cut more freely. However if you have a lot of events to bind and they're not selectors that are very easy to match quickly, this can make event handling slow.
(Because there is no browser-native speedup like querySelectorAll for matching elements against a particular selector as delegation needs to do; this is proposed for Selectors-API level 2.)
var elementCount = $('*').length;
This doesn't really have much to do with jQuery except insofar as it's a handy way to get the answer.
I'm performance-tuning my code, and am surprised to find that the bottleneck is not dom node insert, but selection.
This is fast:
var row = jquery(rowHTML).appendTo(oThis.parentTable);
but the subsequent getting of an element inside "row" is slow:
var checkbox = jquery(".checkbox input", row);
I need to get the checkbox in every row so I can attach an event handler to it. Selecting the checkbox is ALMOST 10X AS SLOW as inserting the entire parent row.
What am I doing wrong here?
DOM manipulation uses native functions to perform simple operations. Browser vendors optimize these. You are building the row from HTML. Internally jQuery is using .innerHTML to build the collection which then patches into the browser's mega-fast parser.
Selection is slow in comparison because JS code needs to loop through the DOM repeatedly. Newer browsers have native selection handling which provides dramatic speedups to selector based JS. As time moves on this will be less of a problem.
Here is how the query in question, $(".checkbox input", row), breaks down:
row.getElementsByTagName('*');
for-loop through every element returned (all elements within the row) and test elements[i].className with /(\s|^)checkbox(\s|$)/.
for-loop every element still remaining and collect matched[i].getElementsByTagName('input');
unique the final collection.
This is different for jQuery 1.3 as it's engine moves through the selector the other way around, beginning with getting all input elements and then testing the parent elements.
Rremember that the JS selector engines implement a lot more of the CSS selector spec than is actually usable with CSS (or implemented by current browsers). Exploiting this, and knowledge of the engines, we can optimize selector can be optimized in a few different ways:
If you know what element type the .checkbox is:
$("td.checkbox input", row);
It is faster for filter first for type and then for the class for only those matches. This doesn't apply for a very small subset of elements, but that is almost never the case in praxis.
The single class test is the slowest of the common selectors people actually use.
Simpler selection:
$("input[type=checkbox]", row);
One loop is faster than two loops. This only finds input elements and then directly filters them by type attribute. Since sub/child-elements are never used, unique may also be skipped (and smart engines will try to do this because unique is slow).
A more direct selector:
$("td:first.checkbox input", row);
A more complex selector may actually be faster if it is more direct (YMMV).
If possible, move the search context up to the table level:
By this I mean that instead of looping through the rows, and searching for the checkbox in every one, leave them alone until after the loop and then select them all at a time:
$("tr td:first.checkbox input", table);
The point of this is to eliminate the overhead of firing the selector engine up repeatedly, but instead do everything in one haul. This is presented here for completeness rather than something that I think would return massive speedups.
Don't select:
Build the row from bits, assigning events as you go.
var row = $( '<tr></tr>' );
var cell = $( '<td class="checkbox"></td>' ).appendTo( row );
$( '<input type="checkbox" name="..."/>' ).appendTo( cell ).click(/* ... */);
This may be impossible for reasons of Ajax or other templates out of your control. Additionally, the speed may not be worth turning your code into this sort of mess, but sometimes this may make sense.
Or, if none of these work for you, or return too performance gain, it may be time to rethink the method entirely. You can assign an event listener higher up the tree and grab the events there, instead of per-element instance:
$('table').change(function(e){
// you may want a faster check...
if ( $(e.target).is('input[type=checkbox]') ) {
// do some stuff ...
}
});
This way you don't do anything unless, and until, the user actually requests it. Fastest. :-)
var checkbox = jquery(".checkbox input", row);
This is traversing the entire dom tree to find the checkbox. You could possibly speed it up by changing the selector to an ID which can use the browsers native getElementById functionality.
var checkbox = jquery("#checkbox input", row);
You could also use your row as a starting point for the DOM search like the following example. Now your not parsing through the entire DOM tree again to find the matched element.
var row = jquery(rowHTML).appendTo(oThis.parentTable);
row.children(".checkbox input");
Use event delegation and add a single handler to a parent element and not the checkboxes themselves.
jQuery supports this via the live() function.
Try putting a class name on the input field itself. That may prove to be faster.
The reason for that is your code goes through all .checkbox classes, tries to find the input child of that element and returns that. I think that action might be your culprit.
By simply just looking for all elements with the class the input field has, you might see some speedup.
Try using Sly, it has an emphasis on performance.
If you're looking for performance, jQuery selectors are very slow. In the example there, it has to scan the full DOM tree and check CSS classes and so on to find the relevant nodes.
It is significantly faster to use native DOM methods. There are some interesting library performance comparisons here:
http://ajaxian.com/archives/taskspeed-more-benchmarks-for-the-libraries-and-browsers
The fastest way to get the DOM element is to use pure JavaScript and calling it by ID.
var element = document.getElementById('element);