user1521604
user1521604

Reputation:

Overhead of calling Jquery on non existing elements for caching reasons

If JQuery calls elements that don't exist, what is the overhead for this? It throws no errors, but other than loading the script is there much cpu overhead? Does it matter if this is done for a class or an id?

For caching reasons and reasons of keeping simultaneous connections at a minimum I keep all my onload scripts for every page in one file, but I was wondering if it would be efficient or not to tell my javascript which page it is on and load only the bits of code that would be actually ran on that page via if statements or switch statements. I don't want to put them in seperate files as I want every page to load as much from cache as possible after the initial visit.

Example you are on the home page, but have product page javascript included in that file or onload.

$('#product_options').hover(function(){},function(){});

But product_options doesn't exist on this page because it's the home page.

And does it make a difference for classes such as

$('.addtocart').click(function(){})

It should be noted this doesn't throw any errors in JQuery.

Upvotes: 2

Views: 667

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239430

There will be a performance hit, simply because work has to be done even to determine there's no matches. Now, in general, this is extremely minor, and it's something you probably won't have to worry about unless you've got a huge very Javascript heady web application -- think Facebook. That said, only running code that should run on the page is still good practice, and the best way I've found for doing that is Paul Irish's method, Markup-based unobtrusive comprehensive DOM-ready execution.

Upvotes: 0

Jon
Jon

Reputation: 437664

jQuery has a special "fast" path to process single id selectors such as #product_options; all other selectors are handled in a much more involved manner. If you keep to id selectors the performance impact is going to be non-measurable.

If you use other selectors then the performance hit will be relatively much greater but in absolute terms it isn't likely to have much impact unless we 're talking about dozens of selectors.

However, you can sidestep all this by putting your code inside functions and then from each page call only those that are relevant. It isn't too much to write in each page

<script type="text/javascript">
$(function() {
    doSomething();
    doSomethingElse();
});
</script>

IMHO this is a nice balance between not dispersing your code across many files while at the same time also not attempting to run dead code.

Upvotes: 2

Related Questions