How to load JavaScript after jQuery.js has loaded in WordPress

To load your custom JavaScript file after jQuery has loaded in WordPress, you need to enqueue your script with jQuery as a dependency.

Here’s how you can do that:

  1. In your WordPress admin dashboard, go to “Appearance” > “Theme Editor.”
  2. In the right sidebar, locate and click on the “functions.php” file.
  3. Add the following code snippet at the end of the file:
function my_theme_enqueue_scripts() {
    // Register your custom script with jQuery as a dependency
    wp_register_script('my-custom-script', get_template_directory_uri() . '/js/my-custom-script.js', array('jquery'), '1.0', true);

    // Enqueue your custom script
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');

Replace /js/my-custom-script.js with the path to your custom JavaScript file.

This code snippet creates a function called my_theme_enqueue_scripts() that registers and enqueues your custom script with jQuery as a dependency. The array(‘jquery’) parameter tells WordPress that your script depends on jQuery, so it will load jQuery before loading your custom script.

  1. Click “Update File” to save the changes.

Now, your custom script will be loaded after jQuery in your WordPress theme.

When using jQuery in your custom script, make sure to use the jQuery object instead of the $ alias, as WordPress runs jQuery in no-conflict mode. You can wrap your code in an immediately-invoked function expression (IIFE) like this:

(function($) {
    // Your custom jQuery code here, using the $ alias
    $(document).ready(function() {
        // Your code that needs to run when the DOM is ready

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

Leave a Reply

Your email address will not be published. Required fields are marked *