Running code only when it is needed is an important aspect of resource management in JavaScript. I use the following method all the time to check if a jQuery element exists before doing something with it.

var $selector = $('.my-element');
if ( $selector.length > 0 ) {
    // Do something with $selector

This approach is awesome, I commonly use it with jQuery’s $.getScript() method to include external JavaScript files into a single JavaScript file only when they’re needed.

var $slideshow = $('.slideshow');
if ( $slideshow.length > 0 ) {
    $.getScript("js/jquery.cycle.min.js").done(function() {

In this example, we only load jquery.cycle.min.js when a .slideshow element is found on the page. This method of loading resources only when they are needed can drastically reduce the size of your JS resources on page load.

As an added bonus, you can also create your own jQuery “exists” function using this simple plugin.

jQuery.fn.exists = function(){ return this.length > 0; }

if ( $(selector).exists() ) {
    // Do something

This dead simple jQuery plugin was contributed by Jake McGraw on StackOverflow. Hopefully this helps you keep your JavaScript files lean and efficient.