Just wandering if it makes sense, to use if statements like below within jquery document ready function to ensure script is only fired if on a specific page..
if(window.location.href.indexOf("our-team")>= 0){
if(window.location.hash) {
var hash = window.location.hash;
$('#teamMembers div:not('+hash+')').hide();
$("#teamMenu .imgHolder").removeClass('active');
$('a[href='+hash+']').closest(".imgHolder").addClass('active');
}
else {
$('#teamMembers div:not(#member1)').hide();
}
}
This is probably not very efficient, but is the if statement necessary to stop the script running if the current page is not containing our-team in the url.
Any ideas guys?
You will obtain the best performance if you don’t run a lot of selector operations on pages that those items don’t exist on. So, if it’s easy to filter out those selector operations by checking the URL or some other quick check, then that may be desirable for performance reasons.
Personally, I prefer to identify page types with a class name on the body tag rather than examining the URL. That means you’re looking more for the expected content rather than where the content came from and if someone managing the site decides to change the URL layout or names, your code won’t be dependent upon that.
Technically speaking, the first if statement is not required if none of the selectors you are using exist in pages that you don’t want to process. But running 4-5 extra selector operations on lots of pages that they don’t apply to is not efficient. And, if every page has this type of code in the common JS and thus it’s 4-5 operations * 50 pages, then that would be a lot of wasted selector operations and could really affect site performance. The more pages you have, the more chance you may repeat a selector in another page and find the JS from one page is accidentally impacting another page too.