如何通过functions.php在网站前端加载脚本但避开Elementor编辑器
问题原因及解决方案
你的代码失效主要有几个关键点,对应的修复方案如下:
1. 未确保Elementor类已初始化
直接调用\Elementor\Plugin::$instance可能在某些场景下(比如钩子触发过早)导致Elementor尚未完成初始化,此时$instance为null,后续的is_edit_mode()判断会失效,脚本/样式依然会被加载。
2. 缺少预览模式的判断
Elementor的前端预览模式(通过预览链接打开的页面)不会被is_edit_mode()识别,但此时也需要排除脚本加载。
3. 钩子优先级不足
默认的wp_enqueue_scripts钩子优先级为10,可能早于Elementor完成编辑状态的初始化,导致判断条件不生效。
修复后的代码:
function mysite_child_enqueue_scripts_styles() { // 非首页直接返回 if ( ! is_front_page() ) { return; } $is_elementor_active = false; // 先确认Elementor类已加载 if ( class_exists('\Elementor\Plugin') ) { $elementor = \Elementor\Plugin::instance(); // 同时检查编辑模式和预览模式 $is_elementor_active = $elementor->editor->is_edit_mode() || $elementor->preview->is_preview_mode(); } // 兜底检查:Elementor预览时会携带的GET参数 if ( isset( $_GET['elementor-preview'] ) ) { $is_elementor_active = true; } // 非Elementor编辑/预览模式下才入队资源 if ( ! $is_elementor_active ) { // 入队样式表 wp_enqueue_style( 'mysite-child-preloader', get_stylesheet_directory_uri() . '/assets/css/preloader.css', array() ); // 入队脚本 wp_enqueue_script( 'mysite-child-modernizr', get_stylesheet_directory_uri() . '/assets/js/modernizr.custom.js', array(), null, true ); wp_enqueue_script( 'mysite-child-scripts', get_stylesheet_directory_uri() . '/assets/js/scripts.js', array(), null, true ); wp_enqueue_script( 'mysite-child-preloader', get_stylesheet_directory_uri() . '/assets/js/preloader.js', array(), null, true ); } } // 提高钩子优先级,确保在Elementor初始化后执行 add_action( 'wp_enqueue_scripts', 'mysite_child_enqueue_scripts_styles', 20 );
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

