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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With