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.

One thought

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.