仅在某些 WP 页面中注册样式是个好主意吗?
Is it a good idea to register style only in certain WP pages?
我有一个页面速度问题,我买的主题真的很糟糕,但我现在不能改变它。我使用 WP_rocket,服务器有 HTTP2,但它仍然需要加载很多资源。所以我尝试将样式数量减少 wp_deregister_style 并仅在需要时加载它。例如 contact-form-7 前端样式我只需要在 .../contact 页面。好主意吗?或者它可能有害?
函数rs_deregister_css(){
global $wp;
$url = home_url( $wp->request);
$contakt = strpos($url,'contakt');
if (!$contakt) {
wp_deregister_style('contact-form-7');
}
}
add_action('wp_print_styles','rs_deregister_css',99);
是的,这对您的加载时间来说是个好主意。但我建议您加载特定的样式,而不是每次检查 URL 并卸载它。
尝试阅读Conditional Tags
function my_enqueue_stuff() {
if ( is_front_page() ) {
/** Call landing-page-template-one enqueue */
wp_enqueue_style( 'your-style-handle', get_stylesheet_directory_uri() . '/yourfile.css' );
} else {
/** Call regular enqueue */
}
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_stuff' );
编辑
由于您只想为特定页面加载样式或 javascript,请将此代码添加到您的 functions.php:
function remove_wpcf7_extras() {
remove_action('wp_print_scripts', 'wpcf7_enqueue_scripts');
remove_action('wp_print_styles', 'wpcf7_enqueue_styles');
}
if( !is_page('contact') ) {
add_action('wp_head', 'remove_wpcf7_extras');
}
是的,这是个好主意,因为您只使用联系页面中的联系表格,别忘了注销 javascript 文件
if (!$contakt) {
wp_deregister_style('contact-form-7');
wp_deregister_script('contact-form-7');
}
我有一个页面速度问题,我买的主题真的很糟糕,但我现在不能改变它。我使用 WP_rocket,服务器有 HTTP2,但它仍然需要加载很多资源。所以我尝试将样式数量减少 wp_deregister_style 并仅在需要时加载它。例如 contact-form-7 前端样式我只需要在 .../contact 页面。好主意吗?或者它可能有害?
函数rs_deregister_css(){
global $wp;
$url = home_url( $wp->request);
$contakt = strpos($url,'contakt');
if (!$contakt) {
wp_deregister_style('contact-form-7');
}
}
add_action('wp_print_styles','rs_deregister_css',99);
是的,这对您的加载时间来说是个好主意。但我建议您加载特定的样式,而不是每次检查 URL 并卸载它。
尝试阅读Conditional Tags
function my_enqueue_stuff() {
if ( is_front_page() ) {
/** Call landing-page-template-one enqueue */
wp_enqueue_style( 'your-style-handle', get_stylesheet_directory_uri() . '/yourfile.css' );
} else {
/** Call regular enqueue */
}
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_stuff' );
编辑
由于您只想为特定页面加载样式或 javascript,请将此代码添加到您的 functions.php:
function remove_wpcf7_extras() {
remove_action('wp_print_scripts', 'wpcf7_enqueue_scripts');
remove_action('wp_print_styles', 'wpcf7_enqueue_styles');
}
if( !is_page('contact') ) {
add_action('wp_head', 'remove_wpcf7_extras');
}
是的,这是个好主意,因为您只使用联系页面中的联系表格,别忘了注销 javascript 文件
if (!$contakt) {
wp_deregister_style('contact-form-7');
wp_deregister_script('contact-form-7');
}