You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gutenberg/ACF区块关联GSAP脚本入队失败及指定页面加载求助

问题解决指南

一、修复ACF区块中GSAP脚本加载失败的问题

你通过ACF区块enqueue_assets加载GSAP时出现GSAP is not defined,核心原因大概率是自定义交互脚本未声明依赖GSAP,或加载顺序有误:

1. 声明脚本依赖关系

如果你的手风琴区块有对应的自定义动画脚本,必须在注册脚本时将gsap-js设为依赖项,示例代码:

'acf_register_block_type(array(
    'name'                => 'lig_large_accordion',
    'title'               => __('LIG large Accordion'),
    'description'     => __('LIG Large Accordion'),
    'render_template'   => 'template-parts/blocks/content-large-accordion.php',
    'icon'                => 'editor-textcolor',
    'keywords'            => array( 'accordion', 'toggle', 'expand', 'info'),
    'category'            => 'design',
    'enqueue_assets'    => function(){
        // 先加载GSAP核心脚本
        wp_enqueue_script( 'gsap-js', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.7.0/gsap.min.js', array(), '3.7.0', true );
        // 加载自定义手风琴脚本,明确依赖GSAP
        wp_enqueue_script( 'large-accordion-script', get_stylesheet_directory_uri() . '/assets/src/accordion/index.js', array('gsap-js'), false, true );
    },
));

2. 验证加载时机

你当前设置GSAP在页脚加载(最后一个参数true),如果页面内有提前执行的内联脚本调用GSAP,会导致报错。可临时将参数改为false(头部加载)测试,确认是否为时机问题。


二、修改脚本加载函数,支持首页+指定页面ID加载

要同时实现首页和特定页面ID加载GSAP,直接修改mytheme_enqueue_front_page_scripts函数的条件判断即可:

修改后的完整代码

function mytheme_enqueue_front_page_scripts() {
    // 定义需要加载GSAP的目标页面ID,可添加多个ID
    $target_page_ids = array(123); // 替换为你的实际页面ID
    // 判断逻辑:是首页 或 当前页面ID在目标列表中
    if( is_front_page() || in_array(get_the_ID(), $target_page_ids) )
    {
        wp_enqueue_script( 'gsap-js', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.7.0/gsap.min.js', null, '3.7.0', true );
    }
}
add_action( 'wp_enqueue_scripts', 'mytheme_enqueue_front_page_scripts' );

关键说明

  • 将$target_page_ids中的123替换为实际需要加载GSAP的页面ID,多个ID用逗号分隔,比如array(123, 456, 789)
  • 保持true参数让脚本在页脚加载,优化页面性能;若有内联脚本依赖GSAP,可改为false

内容的提问来源于stack exchange,提问作者Mr Toad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 03:08:23