How to call Javascript on WordPress the right way

Everyone knows it is mostly unrecommended to hard-code direct calls for js scripts on your templates header. There are many reasons for that, most of them relating to different scripts and api’s incompatibility, that eventually may cause conflicts and wrong behavior of your page. Instead WordPress suggests two core functions to do the same trick:

Usage and differences in short:

The main idea is to always see to that the script is not in conflict with other scripts on the page, and on the other hand, that it has all the required dependencies to work properly. The enqueue_script function should take care of that.

In general Wordress supports most modern Javascript libraries, such as: jquery, mootools, prototype etc., the native library for all WordPress core-utilities being jquery. As a thumb rule, it’s better to always fall back to scripts written and dependent on this library. So our goal is to hook our script on a line of already existing scripts that are all dependent on a basic utility/core script. To achieve this goal we would use the wp-enqueue_script function. This function can get up to 5 parameters (part optional) as detailed: <?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>

$handle – a string representing the label for this script for further reference.

$src (string – optional) – the actual script file name, if not already registered by WordPress. Note that most of the modern Javascript libraries are already registered and can be referred to by their labels alone. For instance, to hook the current jquery core file, we pass only the handle, which is ‘jQuery’. You can find a full reference of all registered scripts in the function’s page on WordPress codex. Scroll a little bit down the page:

$dep (array – optional) an array of all the dependencies that this script should rely on, each dependency is referred to by the label it was enqueued with

$ver (string -optional) – the script version number

$in_footer (boolean – optional) – should this script be called on the footer.

The main goal of this function is to set a script and determine it’s dependencies, so in case these dependencies are not registered – an exception can be handled by WordPress.

Registering a new script

Supposedly we have a new Javascript file, that we want to register with our page. This script is independent to any other scripts on the page, and it is probably not registered yet with WordPress. For that purpose we use the  wp_register_script function. After registering the script, we can refer to it later by pointing to it’s label, at the actual enqueuing:

<?php wp_register_script( $handle, $src, $deps, $ver, $in_footer ); ?>

Note that this functions accepts the same parameters as the wp_enqueue_script function.

For further reading on WordPress api codex, click here: