So here’s an interesting issue. Let’s say you want to have a Nivo Slider on the homepage of your theme. You obviously only want to call that nivoSlider.js if you’re on the homepage. Most of the time you’ll also put your $(window).load function inline with the HTML markup for the slider so you can also wrap it in a is_home conditional. This way your call to the nivoSlider.js and the HTML markup for the slider only show on the homepage.

This isn’t pretty cause we don’t like inline scripts and function calls, right?

So then we can create an external .js file to hold this code

$(window).load(function() {
$('#slider').nivoSlider();
});

There’s a problem with this. You can end up with multiple $(window).load function’s because you may need another function to do something on every part of the site. For example on window load you may want to remove all hard coded pixel based width and height attributes from images.

Here’s a solution for calling the nivoSlider() function ONLY if the #slider selector exists.

$(window).load(function() {
if( $('#slider').length ) {
$('#slider').nivoSlider();
}
});

Now we can keep all our code in one window.load function but only reference the nivoSlider() if we have slides to nivo.

Jesse Friedman has been building websites for 18 years, and exclusively with WordPress since 2006. Since then Jesse has written several books, taught 100’s of students as a professor, and organized dozens of local meetups along with a few WordCamps. Jesse has spoken at tech conferences around the world including SXSW, HOW, Future events and many more. Jesse has consulted for a wide array of companies from small agencies to multi-billion dollar international companies. Today Jesse is a proud team member of Jetpack at Automattic, where he spends his time growth hacking and building strategic partnerships.

One thought

Leave a Reply