jquery - Enqueuing javascript files

admin2025-06-04  53

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...

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...

Share Improve this question asked Dec 20, 2018 at 10:55 JohnGJohnG 3443 silver badges17 bronze badges 5
  • Try to change example-script handler name – Pratik Patel Commented Dec 20, 2018 at 11:02
  • Do you see any error in browser console? – Hector Commented Dec 20, 2018 at 11:16
  • please check js file included in head section your theme – vikrant zilpe Commented Dec 20, 2018 at 12:10
  • second think check js conflict with other file – vikrant zilpe Commented Dec 20, 2018 at 12:11
  • @JohnG could you look at my answer? I have posted a working example. – Remzi Cavdar Commented Dec 20, 2018 at 20:39
Add a comment  | 

3 Answers 3

Reset to default 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 );

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/reference/functions/get_template_directory/#usage

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749028675a315753.html

最新回复(0)