jQuery No Conflict mode and enqueuing scripts in WordPress

I am in the process of registering and enqueuing my JavaScript files properly within WordPress, however jQuery needs some love for this to work properly.

Basically, I have a scripts.js file that I use to add JavaScript enhancements in my themes. This usually includes a document.ready() function:

$(document).ready(function() {
    ...
});

If my scripts.js only included this, then I could pass a reference to jQuery as the $ function into your document.ready() method:

jQuery(document).ready(function($) {
    ...
});

Sometimes in my scripts.js, there are other functions outside of document.ready() that are referenced from within it:

$(document).ready(function() {
    example();
});

$(window).resize(function() {
    example();
});

function example() {
    ...
}

However, for those instances that have stand-alone functions, this was not working in No Conflict mode. To fix this, I had to wrap the entire contents of the file within a self-invoking function:

(function($) {	
    $(document).ready(function() {
        example();
    });

    $(window).resize(function() {
        example();
    });

    function example() {
        ...
    }
})(jQuery);

This solution allows me to retain my current scripts (without having to rewrite the $ to jQuery) and still enqueue the scripts the way that makes WordPress happy.

This is more for my own reference, but someone else may run across this simple but annoying problem.

Leave a Reply

Your email address will not be published. Required fields are marked *