Best practices for adding jQuery or Javascript to WordPress

How to make sure your jQuery code is compatible with WordPress, theme’s and other plugins.

WordPress installations these days are loaded with many plugins. To make sure that your custom plugin, that contains jQuery/Javascript, does not break other plugins it is important to wrap your code in their own private containers.

Page functionality can break when two differen’t libraries from two different plugins conflict with each other.

In JavaScript there is the container called a IIFE. Think of a IIFE as a CLASS(blueprint) in another programming language like PHP.

Immediately Invoke Function Expression.

What it does is, is to wrap code in it own container so that any variable names or methods stay unique inside that container and can’t be picked up or use by other jQuery/JavaScript on the current WordPress installation. Think of it as a isolated container that contains code to not be shared or used by other jQuery/JavaScript libraries or code.

For example of how you would wrap your jQuery/JavaScript in a IIFE

 

Extra:

Code wrapped in a IIFE is referred to as strictly private. Private to the object “class” only. The only way to make variables or functions available to other jQuery/JavaScript libraries is to RETURN to variables or functions in a object. This is a topic for another time.