Advertisement
General

A Beginner's Guide to Enqueuing jQuery

by

One of the best things about WordPress is its vibrant economy. For many users, it's trivially easy to find themes to fit the design for which they're aiming, or to find plugins that provide functionality that they want to introduce into their site.

But how many of you - as developers or designers - have a received that phone call or that email in which the customer claims that something is wrong with their site only to discover that the browser console displays something about an error having to do with JavaScript or jQuery?

Exactly. Most likely anyone who has built and/or maintained a site for someone has come across this problem especially if the end user is given permission to add their own plugins, allow their own updates, etc.

In this post, we're going to review a few concepts around jQuery and WordPress to make sure that we, as developers, are not only working to build our products correctly, but that we also know how to properly diagnose problems as they arise in our customer's sites.


A Word About Including JavaScript Files

This particular topic is not new to Wptuts+. In fact, we've written an extensive article about it before complete with a number of code examples all of which should provide you with everything that you need to understand how to work with JavaScript within WordPress.

But as we continue to observe certain practices going on in the community that we'd love to help resolve, we don't mind covering multiple facets of the same topic.

So, before reading this article, make sure that you're familiar with how to include JavaScript and CSS in your WordPress themes and plugins.


WordPress as a Foundation

When it comes to building products in WordPress, one of the things that we, as developers, need to try to do is to treat the WordPress application as a foundation.

Right now, the API allows us a massive amount of flexibility when it comes to building themes, plugins, and applications, and this is a good thing.

But when we begin to remove libraries that ship with WordPress in favor of our own, it's almost as if we're creating a "mini-fork" of the project.

This isn't a good practice to adopt.

As far as I'm concerned, WordPress ships with its core set of functions and libraries that allow it work the way that it does. Changing out crucial parts of the application - such as jQuery - doesn't only affect WordPress itself, but the entire ecosystem of products that are built on top of it.

Good themes and plugins depend on the presence of those libraries. When we change that functionality, we potentially break every piece of work that's depending on them.

We need to stop viewing WordPress as something that we can take apart and reassemble as we need it, and view it as a foundation off of which to build our own unique work.


Why the Problem of JavasScript Conflicts Exist

Generally speaking, the problem of JavaScript conflicts exist for one of three reasons. A developer has either:

  1. Improperly managed jQuery in their code
  2. Swapped the version of jQuery in favor of another version
  3. Changed the order in which jQuery is loaded

First, any of the above three cases could all be done at once, but more often than not its one of the above. Secondly, I don't think that developers typically do this with ill-intent.

I think it's more of a lack of education and/or understanding of the consequences.

1. Improperly Managing jQuery

By this, I mean that the developer has improperly gained access to the jQuery library either by executing noConflict, not properly returning the variable to its original state, or simply renaming the short cut function.

Later in this article, we'll take a look at the best practice for how to write WordPress-specific jQuery so that it allows us to take full advantage of the library without conflicting with other plugins, themes, or projects.

2. Swapped Versions of jQuery

This is something that is often done with good intent: The idea is that the developer is providing an update to the version of jQuery that's included with WordPress so that new features or more modern jQuery can be written.

The problem with doing this is that previously developed projects aren't written with some of the newer features of the latest version of jQuery. Also, if jQuery has deprecated or completely removed a function in the new version that was present in the old version, then it will prevent that code from working.

3. Change the Order in Which jQuery Is Loaded

Though this is a less common problem, it's something that happens occasionally: In an attempt to help make a site load faster, developers will move the order in which jQuery is loaded further down the page, usually to the footer.

While loading JavaScript in the footer of a page is encouraged by a number of high profile sites, this goes back to thinking of WordPress, holistically, as a foundation for application development.

If WordPress, by default, loads jQuery in a certain location, then we need to remember to leave it there as all works that are built on top of the application are depending on it being in that location and nowhere else.


How to Properly Include jQuery

Though there are a number of different ways that you can prepare your JavaScript source files to use jQuery, there's one way that I tend to follow because it completely protects and encapsulates the $ function.

(function( $ ) {
	"use strict";

	$(function() {

		// Your code here

	});

}(jQuery));

You can also view the GitHub gist here.

In short:

This provides a properly loaded version of jQuery that uses the standard $ function reference to allow us to continue going about our work.

Note that the "use strict" statement provides the following:

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This strict context prevents certain actions from being taken and throws more exceptions

For those who are interested, you can read more about that at this site.

Finally, the actual document.ready function is optional. Here, it's used just to show how you can begin using the standard jQuery functions within the context of the code.


Conclusion

Note that the next version of WordPress is planning to ship with a patch that will make this particular discussion obsolete, at least as far as the Dashboard goes.

Specifically, there is currently a ticket in Trac in which WordPress will not allow us to remove jQuery from the Dashboard. That's a good thing.

In short, the main takeaways for this article are as follows:

  • Use the version that ships with WordPress
  • Gain access to the $ function using proper JavaScript facilities

I'd say that doing anything else is setting yourself up for potentially bad results.

Related Posts
  • Code
    Articles
    Introduction to WordPress App ThemesApp theme 400
    With the increasing growth rate of WordPress powered websites, the need for WordPress themes is rising. Multi-purpose themes are becoming highly popular among website owners. Many existing themes are built mainly to address blog functionality. But with the growth of WordPress web application development, we are in need of specialized themes for different purposes. These themes are known as app themes. In this article, we going to familiarize with the concept of app themes and their usage in real world.Read More…
  • Code
    Theme Development
    How to Pass PHP Data and Strings to JavaScript in WordPressPhp js 400
    It's good practice to put all your data in static strings in your PHP files. If you need to use some data in JavaScript later on, it's also good practice to put your data as data-* attributes in your HTML. But in some certain scenarios, you have no choice but to pass strings directly to your JavaScript code. If you are including a JavaScript library, and you've found yourself initializing a JavaScript object inside your header.php then assigning data to its properties, then this article is for you. This article will teach you on how to properly pass PHP data and static strings to your JavaScript library.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme From Static HTML: Releasing Your ThemeCreating wordpress theme from html 400
    If you've been following this series you now have a working WordPress theme. Your theme has a number of template files, including a page template and an archive template, and also has featured image support.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: A ReviewApplication foundation 400
    Over the past few months, we've been taking a look at all of the features and aspects that make WordPress a potential foundation for application development. In fact, we've spent roughly 15 articles talking about all that WordPress offers. And though we'll be reviewing each of the points in this email, perhaps the biggest thing to take away that building web applications using WordPress is different than using many of the popular frameworks that are currently available namely because WordPress isn't a framework.Read More…
  • Code
    Articles
    WordPress Initialization Hooks: Benefits and Common MistakesHooks
    In programming, initialization of data is important as it's where we setup the prerequisites for the application such as its attributes, its required files and data, its connection to the database, and so on. WordPress itself has a well-defined initialization procedure. Through the page life cycle, WordPress fires a number of actions many of which we've covered in previous articles. To that end, it provides a set of initialization hooks which are naturally used to initialize the application before executing its primary functionality. As plugin and theme developers, it's important to understand the use cases and common mistakes of these initialization hooks, in order to build quality applications. In this article, we are going to take a look at the importance of WordPress initialization hooks and how they are used in various scenarios.Read More…
  • Code
    Theme Development
    Integrating the Envato WordPress Toolkit to Your Theme: The PluginEnvato toolkit 400
    As WordPress authors in ThemeForest, we like to make our customers happy by providing them with occasional bug fixes and enhancements to our themes. But one key problem for us is how to notify our users when an update is available for download.Read More…