我正在为每个页面和类别生成关键的CSS。目前,我正在通过functions.php插入样式表,就像这样,只使用echo。
function criticalCSS_wp_head() {
if (is_front_page() ){
echo '<style>';
include get_stylesheet_directory() . '/css/critical/ccss-index.min.css';
echo '</style>';
}
elseif (is_category('orange') ){
echo '<style>';
include get_stylesheet_directory() . '/css/critical/ccss-orange.min.css';
echo '</style>';
}
elseif (is_page('hello-world') ){
echo '<style>';
include get_stylesheet_directory() . '/css/critical/ccss-hello-world.min.css';
echo '</style>';
}
elseif (is_single() ){
echo '<style>';
include get_stylesheet_directory() . '/css/critical/ccss-single.min.css';
echo '</style>';
}
}
add_action( 'wp_head', 'criticalCSS_wp_head' );自从回答了这个问题之后,我忘了提到关键的CSS需要在DOM中内联,而不是作为文件链接,以避免呈现阻塞。因此,我仍然在寻找一种方法来使用关键的CSS与wp_enqueue_scripts。或者将文件内容存储在一个变量中,并在wp_enqueue_scripts请求时输出它?
发布于 2017-04-11 14:19:56
你可以这样做,把它放在你的functions.php中:
这是正确的做法,它的“WordPress方式”。
<?php
// Check if function exisits
if (!function_exists('rg_templateScriptSetup')) {
// if not, create one
function rg_templateScriptSetup() {
// Register styles in WordPress
wp_register_style('prefix-basic-css', get_template_directory_uri(). '/css/basic-style.css');
// Register styles in WordPress
wp_register_style('first-css', get_template_directory_uri(). '/css/first-style.css');
// Register styles in WordPress
wp_register_style('second-css', get_template_directory_uri(). '/css/second-style.css');
if (is_page('your_page_name') {
// enqueue your first style
wp_enqueue_style('first-css');
} else if(is_page('your_other_page_name')) {
// enqueue your second style
wp_enqueue_style('second-css');
} etc...
} // End of Stylesheet logic / setup
add_action('wp_enqueue_scripts', 'rg_templateScriptSetup');
?>为什么?
因为WordPress为您提供了实现该目标所必需的所有工具。
这里到底发生了什么:
我希望这能帮上忙。
如果这个答案对您有帮助,请将其标记为正确,而不是仅仅抓取代码,谢谢。
个人问题:批评是什么意思?很多!重要吗?
发布于 2017-04-11 14:38:02
添加CSS或JS的最佳实践和普遍接受的正确方法是对它们进行排队。这样的话,如果你有一个主题+2个插件,所有这些插件都想让jQuery排队,那么你只能加载一个拷贝,而不是3个拷贝。
在functions.php中:
add_action('wp_enqueue_scripts', 'my_enqueues');
function my_enqueues() {
if(is_front_page()) {
wp_enqueue_style('front-page', get_stylesheet_directory() . '/css/critical/ccss-index.min.css', array(), '', 'screen');
} elseif(is_category('orange')) {
wp_enqueue_style('orange', get_stylesheet_directory() . '/css/critical/ccss-orange.min.css', array(), '', 'screen');
}
}如果您的每页样式是短的,您实际上可以加入内联样式,这样网页浏览器就不会请求单独的资源。
add_action('wp_enqueue_scripts', 'my_inline_enqueues');
function my_inline_enqueues() {
wp_add_inline_style('front-page',
'.myfrontpageclass { font-size:6em; }'
);
}最后一个建议--我不知道样式表的内容,但我建议,如果您只是将所有CSS都包含在主题的style.css文件中,那么加载这些页面可能会更简单、更快。使用body_class来瞄准您需要的任何东西,并将其保存在一个缩小的文件中。
https://wordpress.stackexchange.com/questions/263268
复制相似问题