A common mistake made by beginning theme and plugin developers is to bundle their theme or plugin with their own version of the library. This may conflict with other plugins that enqueue the version bundled with WordPress. As a best practice, make your theme compatible with the version of your favorite library included with WordPress.
- Avoid Global Variables
- Use closures and the module pattern
- Validate and Lint Your Code – ESLint.com
- Lazy load assets that aren’t immediately required.
array( 'jquery' ) ensures that the jQuery script has been downloaded and loaded before your theme’s code.
Because the copy of jQuery included in WordPress loads in (link needed)
noConflict() mode, use this wrapper code in your theme’s .js files to map “$” to “jQuery”:
This wrapper (called an Immediately Invoked Function Expression, or IIFE) lets you pass in a variable—jQuery—on the bottom line, and give it the name “$” internally. Within this wrapper you may use
$ to select elements as normal.
Every time you select an element with jQuery, it performs a query through your document’s markup. These queries are very fast, but they do take time—you can make your site respond faster by re-using your jQuery objects instead of using a new query. So instead of repeating selectors:
it is recommended to cache your selectors so you can re-use the returned element without having to repeat the lookup process:
When you use jQuery methods like
.click, jQuery creates a new browser event object to handle processing the requested event. Each new event created takes a small amount of memory, but the amount of memory required goes up the more events you bind. If you have a page with a hundred anchor tags and wanted to fire a `logClick` event handler whenever a user clicked a link, it is very easy to write code like this:
This works, but under the hood you have asked jQuery to create a new event handler for every link on your page.
Event delegation is a way to accomplish the same effect with less overhead. Because events in jQuery “bubble”—that is, a click event will fire on a link, then on the link’s surrounding
<p> tag, then on the
div container, and so on up to the
document object itself—we can put a single event handler higher up in the page structure, and still catch the click events for all of those links: