1

I'm trying to enqueue a JS file (located at /js/example-script.js), just to get an alert on page load.

Can anyone tell me what I'm doing wrong?

In my example-script.js:

jQuery(document).ready(function($) {
  alert("hi");
});

And in my functions file:

function my_theme_scripts() {
    wp_enqueue_script( 'example-script', get_template_directory_uri() . '/js/example-script.js', array( 'jquery' ), '1.0.0', true );
}

add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );

jQuery is loaded in my sources, so that's not the problem...

5
  • Try to change example-script handler name Dec 20, 2018 at 11:02
  • Do you see any error in browser console?
    – Hector
    Dec 20, 2018 at 11:16
  • please check js file included in head section your theme Dec 20, 2018 at 12:10
  • second think check js conflict with other file Dec 20, 2018 at 12:11
  • @JohnG could you look at my answer? I have posted a working example. Dec 20, 2018 at 20:39

3 Answers 3

1

Example for themes

I would recommend using wp_enqueue_script with get_theme_file_uri this allows child themes to overwrite this file.

get_theme_file_uri() function

Searches in the stylesheet directory before the template directory so themes which inherit from a parent theme can just override one file.

wp_enqueue_script( 'example-script', get_theme_file_uri( '/js/example-script.js' ), array('jquery'), null, true );


Example for plugins

wp_enqueue_script( 'example-script', plugins_url('/js/example-script.js', __FILE__), array(), null );
1

Are you using a child theme ? In this case you have to use get_stylesheet_directory_uri() instead of get_stylesheet_template_uri()which returns the parent theme uri https://developer.wordpress.org/reference/functions/get_template_directory/#usage

0

All answers correct - in my case I'd done it right, just wasn't loading the WP Footer, despite jQuery showing in my sources. As soon as I added in get_footer(), all worked fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.