简体   繁体   中英

how do i use wp_enqueue_script?

OK, so this is in my functions.php file: (the following is the edited version to utilize cool's answer below. I'm leaving the original afterward:

function mdg_setup_scripts() {
  wp_register_script( 'hoverIntent', get_bloginfo('template_url').'/js-custom/hoverIntent.js', array( 'jquery' ));
  wp_enqueue_script( 'hoverIntent' );
  wp_register_script( 'mdMenuAnimation', get_bloginfo('template_url').'/js-custom/mdMenuAnimation.js', array( 'jquery' ));
  wp_enqueue_script( 'mdMenuAnimation' );
}
add_action( 'wp_enqueue_scripts', 'mdg_setup_scripts' );

Here's what I originally had:

function mdg_setup_scripts() {
  wp_register_script( 'hoverIntent',
    get_bloginfo( 'template_url' ) . '/js/hoverIntent.js',
    array( 'jquery' ),
    false,
    true );
  wp_register_script( 'mdMenuAnimation',
    get_bloginfo('template_url') . '/js/mdMenuAnimation.js',
    array( 'jquery', 'hoverIntent' ),
    false,
    false );
  if (!is_admin()) {
    wp_enqueue_script( 'mdMenuAnimation' );
  }
}
add_action( 'init', 'mdg_setup_scripts' );

The js files are present in the indicated folder. But no JavaScript at all is loading on the front end. I'm doing something wrong, but what? Do I need to register jquery (I thought WP had jquery in it, though)? Do I need to separate the enqueue call? Do I need to add something to my header.php?

You dont need to add jquery. If it is not added, and if your custom script depends on it (like you wrote in code) it will be added by wordpress. This code will work (i just tested it) but..

Instead of this:

if (!is_admin()) {
    wp_enqueue_script( 'mdMenuAnimation' );
}

wordpress recomed that you use hooks:

Wordpress-codex: Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side.

So it should be something like this:

function my_scripts_method() {
   wp_register_script( 'somehover', get_bloginfo('template_url').'/js-custom/hoverIntent.js', array( 'jquery' ));
   wp_enqueue_script( 'somehover' );
}  

add_action('wp_enqueue_scripts', 'my_scripts_method');

Wordpress-codex: by using the wp_enqueue_scripts hook (instead of the init hook which many articles reference), we avoid registering the alternate jQuery on admin pages, which will cause post editing (amongst other things) to break after upgrades often.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM