The Right Action Hook
There are three action hooks we can use to enqueue Javascript. The right action hook depends on where we want to load the JavaScript. These are the three action hooks:
- wp_enqueue_scripts action hook should be used if we want JavaScript to be loaded on the front-end
- admin_enqueue_scripts action hook should be used if we wanna load JavaScript on the admin screens (back-end)
- login_enqueue_scripts action hook should be used in order to load JavaScript on the login screen
wp_enqueue_script() Function
In order to load JavaScript on a WordPress site we use the wp_enqueue_script() function. This function receives 5 parameters:
- Handle: unique name of the script
- Source: path of the script
- Dependencies: an array of the handles of other script that this one depends on
- Version: a string specifying the version
- In Footer: a boolean that determines if the script should be loaded in the footer instead of the header
So to load a JavaScript on all front-end pages we can use something like this in our theme:

In order to load JavaScript on the front-end of specific pages

wp_localize_script() Function
There are situations when we wanna pass some data from PHP (back-end) to JavaScript (front-end). You can use the wp_localize_script() to do that. This function lets us add a JavaScript object from PHP and make it available to a specific script. This function gets three parameters:
- Handle: the handle of the JavaScript we wanna add the object to
- Object Name: the name of the JS object that will be available in the front-end
- Data: an array with the data that will be available in the object
For instance if we want the front-end JavaScript to have access to an object called “js_object” with some data we can use something like this:

This will add the localized object as a JS variable on pages that load the script. This is how the page source code looks:

Then, in JavaScript we’ll have access to an object like this:

One of the best use cases of sending data from PHP to JS using wp_localize_script() is for nonces. We can create the nonce in PHP and then pass it to JS. Later. on when we wanna make an AJAX call from the JS to the backend, we also pass the nonce to PHP to be verified.
To see an example of this you can check this PHP code and this JS code on GitHub.