据我了解,管理脚本应该通过admin_enqueue_scripts
钩子和所有其他脚本进行注册和入队,wp_enqueue_scripts
因此我设置了以下功能,以一种清晰且有组织的方式注册和入队所有脚本。
我的问题是,如果我在admin和前端都需要某些脚本(例如jquery validate插件)怎么办?在这种情况下,建议使用什么方法来注册和排队脚本?用不同的$ handle注册两次或wp_enqueue_scripts
仅通过$ handle注册,如果是这样,是否不存在在需要时不被调用的风险?(我的意思是,admin_enqueue_scripts
如果不更早提供这些脚本,为什么还会存在其他原因?
我真的很感谢有人向我解释这一点,以充分理解wp中排队脚本的细微差别。谢谢
我的代码:
// REGISTER ALL NON-ADMIN SCRIPTS
add_action( 'wp_enqueue_scripts', 'register_all_non_admin_scripts' );
function register_all_non_admin_scripts() {
wp_register_script( ... );
wp_register_script( ... );
}
// ENQUEUE NON-ADMIN SCRIPTS CONDITIONALLY
add_action( 'wp_enqueue_scripts', 'enqueue_scripts_where_required' );
function enqueue_scripts_where_required() {
// scripts to be loaded at all times
wp_enqueue_script( '' );
// scripts to be loaded conditionaly
if( is_page( '' ) ) {
wp_enqueue_style( '' );
}
}
// REGISTER ALL ADMIN SCRIPTS
add_action( 'admin_enqueue_scripts', 'register_all_admin_scripts' );
function register_all_admin_scripts(){
wp_register_script( ... );
wp_register_script( ... );
}
// ENQUEUE ADMIN SCRIPTS
add_action( 'admin_enqueue_scripts', 'enqueue_admin_contact_cpt_js' );
function enqueue_admin_contact_cpt_js(){
global $post_type;
// scripts to be loaded at all times
wp_enqueue_script( '' );
// scripts to be loaded conditionaly by post type
if( 'contact' == $post_type ){
wp_enqueue_script( '' );
...
}
}