WordPress has been in our lives for over 16 years, yet the method of adding scripts to themes and plugins still remains a mystery for many developers. In this article we finally put the confusion to rest.
About jQuery’s Compatibility Mode
Before we start attaching scripts to WordPress, it’s important to understand jQuery’s compatibility mode.
As you’re probably aware, WordPress comes pre-loaded with jQuery, which you can use with your code.
WordPress’ jQuery also has a “compatibility mode,” which is a mechanism for avoiding conflicts with other language libraries.
Part of this defense mechanism means you cannot use the
$ sign directly as you might in other projects.
Instead, when writing jQuery for WordPress you need to use
Check out the code below for an example:
The problem is, writing jQuery a gazillion times takes longer, makes it harder to read, and can bloat your script.
The good news?
With a few modifications you can go back to using our lovely little dollar sign once again.
BTW, if you’re new to jQuery, the $ sign is just an alias to jQuery(), then an alias to a function.
The basic structure looks like this:
$(selector).action(). The dollar sign defines jQuery… the “(selector)” queries or finds HTML elements… and finally the “jQuery action()” is the action to be performed on the elements.
Back to how we can get around our compatibility issue… here are a couple of viable options:
1.Enter jQuery Stealth Mode
The first way to get around compatibility mode is to get stealthy with your code.
For example, if you’re loading your script in the footer, you can wrap your code in an anonymous function, which will map jQuery to
Like in the example below:
If you want to add your script in the header (which you should avoid if possible, more on that below) you can wrap everything in a document-ready function, passing
$ along the way.
2.Enter “No Conflict” Mode
Another simple way to avoid spelling out jQuery is to enter “no conflict” mode and use a different shortcut.
In this case:
$j instead of the default
All you have to do is declare this at the top of your script:
var $j = jQuery.noConflict();
Alright, now you know more about writing valid jQuery code for WordPress, let’s add it to our website.
Steps To Add jQuery Scripts To WordPress
- Add jQuery scripts to WordPress via enqueueing
- Add Scripts to WordPress Admin
- De-Register WordPress’jQuery
- Shouldn’t You Register Scripts Before
This article was written by Daniel Pataki and originally published on WPMU DEV Blog.