如何在WordPress function.php引入AMP<amp-script>并在AMP页面加载
WordPress function.php 引入amp-script组件实现AMP页面正常加载方案
以下方案基于官方AMP插件实现,第三方自定义AMP适配方案不保证兼容。
步骤1:注册amp-script组件脚本
AMP默认不会自动加载全量组件,需要通过官方提供的过滤器主动声明加载amp-script组件,将以下代码加入主题functions.php文件:
// 注册amp-script组件到AMP页面资源加载列表 add_filter( 'amp_component_scripts', function( $component_scripts ) { $component_scripts['amp-script'] = 'https://cdn.ampproject.org/v0/amp-script-0.1.js'; return $component_scripts; }, 10, 1 );
步骤2:将amp-script加入标签白名单
AMP自带的HTML安全校验逻辑会默认拦截不在白名单内的标签和属性,不加白名单的话你写的amp-script标签会被自动过滤掉,继续在functions.php中追加以下代码:
// 配置amp-script标签允许的属性,加入AMP安全校验白名单 add_filter( 'amp_kses_allowed_html', function( $allowed_tags ) { $allowed_tags['amp-script'] = [ 'src' => true, 'layout' => true, 'width' => true, 'height' => true, 'script' => true, 'sandbox' => true, 'class' => true, 'id' => true, 'credentials' => true, 'crossorigin' => true, ]; return $allowed_tags; }, 10, 1 );
步骤3:组件使用示例
配置完成后就可以在AMP页面正常使用amp-script组件了,注意遵守AMP的组件规则:
所有amp-script加载的自定义JS总大小不得超过150KB,JS的DOM操作范围不能超出amp-script标签包裹的节点,否则会被AMP运行时直接拦截报错。
外链JS用法
<amp-script layout="container" src="https://你的站点域名/wp-content/themes/当前使用主题名/js/custom-amp-logic.js" class="custom-amp-module" > <!-- 仅此处的DOM节点可以被上述外链JS操作 --> <div class="interactive-container"></div> </amp-script>
内联JS用法
内联JS必须指定target="amp-script"和type="text/plain"属性,否则不会被识别执行:
<amp-script layout="container" class="inline-js-demo"> <button id="countBtn">点我计数</button> <p>累计点击:<span id="countNum">0</span></p> <script type="text/plain" target="amp-script"> const btn = document.getElementById('countBtn'); const numEl = document.getElementById('countNum'); let clickCount = 0; btn.addEventListener('click', () => { clickCount += 1; numEl.textContent = clickCount; }); </script> </amp-script>
常见踩坑说明
- 所有加载的JS资源必须走HTTPS协议,HTTP资源会被AMP直接拦截
- 不要修改amp-script组件的CDN地址,必须使用ampproject官方CDN资源,否则会触发AMP校验失败
- 官方AMP插件的三种模式(标准模式、过渡模式、读者模式)下上述代码均通用,不需要调整钩子优先级
- 配置完成后可以到AMP插件自带的校验工具页面扫描,确认没有amp-script相关的报错
内容的提问来源于stack exchange,提问作者bruse li
相关产品推荐
相关产品推荐

