函数用法:
<?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>
参数解释:
-
$handle
:用于区别 JS 名称,即标识字串 (string); $src
:JS 的文件 URL (string);$deps
:加载的 JS 所依存的其他 JS 标识字串数组 (array:string, 非必需);$ver
:JS 的版本号,留空则使用当前 WP 版本号 (string, 非必需);$in_footer
:是否放置到网页 HTML 底部加载 (boolean, 非必需)。
示例:
/**
* Register and Enqueue Scripts.
*/
function twentytwenty_register_scripts() {
$theme_version = wp_get_theme()->get( 'Version' );
if ( ( ! is_admin() ) && is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
wp_enqueue_script( 'twentytwenty-js', get_template_directory_uri() . '/assets/js/index.js', array(), $theme_version, false );
wp_script_add_data( 'twentytwenty-js', 'async', true );
}
add_action( 'wp_enqueue_scripts', 'twentytwenty_register_scripts' );
<?php
function my_enqueue_scripts() {
if( !is_admin ) { // 前台加载的脚本与样式表
// 去除已注册的 jquery 脚本
wp_deregister_script( 'jquery' );
// 注册 jquery 脚本
wp_register_script( 'jquery', get_template_directory_uri() . '/js/jquery.js', false, '1.0', false );
// 提交加载 jquery 脚本
wp_enqueue_script( 'jquery' );
}
}
// 添加回调函数到 init 动作上
add_action( 'init', 'my_enqueue_scripts' );
?>
有依赖关系(该js依赖“jquery”):
//全局加载js脚本
wp_enqueue_script( 'twentyfifteen-script', get_template_directory_uri() . '/js/functions.js', array( 'jquery' ), '20141212', true );
参考