Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jQuery handle elements that don't exist on a page?

Tags:

jquery

I have kind of a theory question on what happens when you have jQuery searching for elements/binding to elements that do not exist on a page.

For example, I have a javascript file that contains many Click events, however on some pages, those click events aren't used. Rather than making multiple javascript files and having duplicate code, I have minified most of my code down to one file.

$('#target').click(function() {
    alert('Handler for .click() called.');
});

Basically to sum up my paragraph into a few simple sentences. What happens when id "target" doesn't exist? How does jquery handle a case like this?

Now, whenever I work on my website, it seems like FireFox's memory usage grows like crazy. Not sure if this is just FireFox or not, but if I don't have element on the page, is this causing memory leaks by binding to elements that don't exist?

Just curious what happens behind the scene.

Thanks!

like image 803
user1110302 Avatar asked Feb 14 '12 22:02

user1110302


2 Answers

If no elements match your selector, you'll get an empty jQuery object (one that contains no elements).
Calling any method except live() on an empty jQuery object will do nothing at all and will not waste resources.

like image 143
SLaks Avatar answered Oct 22 '22 16:10

SLaks


jQuery always works on lists of elements. When the selector doesn't match anything, you get an empty list, and manipulating that does nothing.

Attaching events to nonexistent elements like doesn't actually do anything, so no, that's not leaking memory.

like image 40
Matti Virkkunen Avatar answered Oct 22 '22 15:10

Matti Virkkunen