WordPress Development: Properly load your Javascript and set dependency

Theme and Plugin developers should wp_enqueue_script() to load the Javascript sources used in their code. Why should you enqueue? In the first place you should prevent conflict between your scripts. Secondly you should only load the resources you need per page. Load the right scripts only will reduce your load time.

WordPress offers a list of bundled resources like jQuery. So you don’t have to load jQuery every time, but you will have to set the dependency of jQuery of the sources you add.

Enqueueing you scripts proper will also help other theme and plugin developers. When two plugin need the same Javascript library you will load it only once. You will have to realize this in not guaranteed and documented well. If two plugins for example need some plugins of Twitter’s Bootstrap there will be no rules to describe the source already loaded. A solution can be both plugins depends on a third plugin which loads the resources. This kind of dependency is outside the scope of this blog post.

Although the reasons for proper loading seems clear many plugins and themes haven’t enqueued all their code.

Why do developers skip wp_enqueue_script()?

The main reason i found was the use of dynamic variables. Enqueued scripts load before the theme or plugin functions have been parsed in many situations. For example you will set the width of an element by javascript where the width will be user defined. The easiest but wrong solution will be to write it direct to source. Write javascript to source and for example make use of jQuery’s document ready will create a dependency of jQuery.

Solutions to use dynamic variables with wp_enqueue_script:

The first solution will be to write your code in native javascript not dependent of any library.
The second, and preferred solution in my opinion, is to (mis)use the wp_localize_script() function. wp_localize_script() localizes a script, but only if script has already been added. Can also be used to include arbitrary Javascript data in a page. The latest can be used to set your dynamic variables. Also read: Use wp_localize_script, It Is Awesome
Some example:

/** set parameters for display **/

$options = array();
$options[‘color’] = get_option( ‘color’, ‘blue’ );

wp_register_script( ‘color_display’, plugin_dir_url( __FILE__).’display_color.js’, array( ‘jquery’ ), ‘20131108’ );
wp_enqueue_script( ‘color_display’ );
wp_localize_script(‘color_display’, ‘color_display_options’,$options)

With display_color.js:

jQuery(document).ready(function($) {
$('colored').css('background-color',color_display_options.color);
};

Defer loading plugin

Recent i wrote a plugin for Defer loading. This plugin requires scripts are enqueued proper. Testing this i found many issues with different

plugins:

One Response to “WordPress Development: Properly load your Javascript and set dependency”

Leave a Reply

(will not be published)