I posted another question on a very similar topic, but turned out to be a little subjective. I am able to divided the question in two questions, one that I will explain below:
In the following Code:
<script type="text/javascript">
$(function()
{
$("#accordion").accordion();
$("#datepicker").datepicker();
$("#button").click(function()
{
runEffect();
return false;
});
});
</script>
Question: If I have this code called in a 1,000 pages, but only 250 pages have a datepicker id. Will the browser spend extra time on the other 750 pages trying to parse for id datepicker, or Jquery has a smart way of solving this situation without affecting performance?
What happen if the code is making reference to ids or classes that does not exist on the html markup of the current page, will that impact performance?
For those saying "don't worry about it" I couldn't disagree more.
I built a site like this once where the external JS file had:
$(function() {
// do lots and lots of stuff
});
with no Javascript internally on the HTML (PHP) page. It was a performance disaster and that was with relatively efficient selector choice, meaning never:
$(".someClass").doStuff();
Instead:
$("div.someClass").doStuff();
and so on. It took about a second to execute all the Javascript even though 95% of it was doing nothing. My advice? If you want a highly responsive Web site don't do it this way.
Instead put functions like this in your external JS:
function activate_accordion() {
$("#accordion").accordion();
}
This is of course a simple example. But the point is this: no Javascript should be automatically executed in your external Javascript file unless the vast majority of pages use it. Your external Javascript file should just be a collection of functionality that is called where necessary on individual pages.
and then on each page inside the HTML put:
<script type="text/javascript">
$(function() {
activate_accordion();
}
</script>
so you only execute the Javascript you are actually using. Yes this is slightly more work because you have to be aware of what each page is doing/using but doing it globally can quickly get out of hand.
I reduce the Javascript execution times to 50-100ms (from 1-2 seconds) this way.
It will look for such an element, and, since there aren't any, it won't do anything.
jQuery's selector library is highly optimized for performance, so I wouldn't worry about it.
In particular, a simple #id
selector is turned into a call to the browser's native getElementById
, which can be assumed to be quite fast.
If you're really concerned, measure it in different browsers.
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