如何在WordPress DIVI主题中设置子主题CSS文件最后加载
实现Divi子主题CSS全站最后加载的可行方案
方案1:调整挂载优先级+声明动态样式依赖
适合Divi动态缓存样式通过WordPress标准wp_enqueue_style挂载的场景,修改你原来的入队代码如下:
add_action( 'wp_enqueue_scripts', 'divi_engine_dynamic_child_theme', 9999 ); function divi_engine_dynamic_child_theme() { wp_enqueue_style( 'parent-theme', get_template_directory_uri() . '/style.css', array(), et_get_theme_version() ); wp_dequeue_style( 'divi-style' ); // 收集所有Divi生成的动态缓存样式作为依赖 $deps = array( 'parent-theme' ); global $wp_styles; foreach ( $wp_styles->registered as $handle => $style ) { if ( strpos( $handle, 'cached-inline-styles' ) !== false ) { $deps[] = $handle; } } wp_enqueue_style( 'child-theme', get_stylesheet_uri(), $deps, filemtime( get_stylesheet_directory() . '/style.css' ) ); }
逻辑说明:将子主题样式的挂载优先级拉到9999,同时把所有Divi生成的cached-inline-styles样式设为依赖,确保子主题样式在所有匹配的依赖样式加载完成后才加载。
方案2:通过Divi原生过滤器追加子主题样式
如果方案1不生效,说明Divi是通过print直接输出动态样式(即源码中can_enqueue为false的分支),可直接用Divi源码暴露的et_core_page_resource_tag过滤器实现追加:
// 先注释/删除你原来的divi_engine_dynamic_child_theme相关入队代码,避免重复加载子主题CSS add_filter( 'et_core_page_resource_tag', 'append_child_css_after_divi_dynamic', 9999, 2 ); function append_child_css_after_divi_dynamic( $tag, $slug ) { static $child_css_added = false; // 匹配到最后一个动态缓存样式时追加子主题CSS if ( strpos( $slug, 'cached-inline-styles' ) !== false && ! $child_css_added ) { $child_css_path = get_stylesheet_directory() . '/style.css'; $child_css_url = get_stylesheet_uri(); $ver = filemtime( $child_css_path ); $tag .= sprintf( '<link rel="stylesheet" id="child-theme-final" href="%s?ver=%s" type="text/css" media="all" />', esc_url( $child_css_url ), esc_attr( $ver ) ); $child_css_added = true; } return $tag; }
逻辑说明:直接对接Divi的动态样式输出逻辑,不管Divi是标准入队还是直接打印输出,都能保证子主题CSS在所有Divi动态样式之后加载,兼容性更强。
方案3:页脚末尾挂载子主题样式
如果前两个方案存在插件兼容问题,可选择最稳妥的页脚挂载方案,100%保证子主题CSS是全站最后加载的样式:
// 先注释/删除你原来的divi_engine_dynamic_child_theme相关入队代码 add_action( 'wp_footer', 'load_child_css_at_footer_last', 9999 ); function load_child_css_at_footer_last() { $child_css_path = get_stylesheet_directory() . '/style.css'; $child_css_url = get_stylesheet_uri(); $ver = filemtime( $child_css_path ); ?> <link rel="stylesheet" id="child-theme-final" href="<?php echo esc_url( $child_css_url . '?ver=' . $ver ); ?>" type="text/css" media="all" /> <?php }
注意事项:该方案可能出现极短时间的样式闪烁(FOUC),如果对首屏加载体验要求高不建议使用。
内容的提问来源于stack exchange,提问作者Julian
相关产品推荐
相关产品推荐

