amp-script
Description
在Web Worker中运行自定义JavaScript。
Required Scripts
<script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>
Supported Layouts
用法
amp-script 组件允许您运行自定义JavaScript。为了保持AMP的性能保证,您的代码在Web Worker中运行,并且存在某些限制。
amp-script 元素可以通过两种方式加载JavaScript:
- 远程, 从一个URL
- 本地, 从页面上的
<script>元素
从远程URL加载JavaScript
使用该src属性从URL加载JavaScript:
<amp-script layout="container" src="https://example.com/hello-world.js"> <button>Hello amp-script!</button> </amp-script>
从本地元素加载JavaScript
你也可以将你的JavaScript嵌入到一个 script 标签中。你必须:
- 设置你的
amp-script的script属性为本地script元素的id. - 在你的
target="amp-script"中包含amp-script。 - 在你的
script中包含type="text/plain"这样,浏览器就不会执行你的脚本,而允许amp-script来控制它。
<!-- To use inline JavaScript, you must add a script hash to the document head. --> <head> <meta name="amp-script-src" content="sha384-YCFs8k-ouELcBTgzKzNAujZFxygwiqimSqKK7JqeKaGNflwDxaC3g2toj7s_kxWG" /> </head> ... <amp-script width="200" height="100" script="hello-world"> <button>Hello amp-script!</button> </amp-script> <!-- Add [target="amp-script"] to the <script> element. --> <script id="hello-world" type="text/plain" target="amp-script"> const btn = document.querySelector('button'); btn.addEventListener('click', () => { document.body.textContent = 'Hello World!'; }); </script>
出于安全原因,带有
script或跨域src属性的amp-script 元素需要在 <meta name="amp-script-src" content="..."> 标签中使用script hash。同样, 同源的 src 文件必须有 Content-Type: application/javascript 或 text/javascript。 它是如何工作的?
amp-script 在一个可以访问虚拟DOM的 Web Worker 中运行你的定制JavaScript。 当你的JavaScript代码修改这个虚拟DOM时, amp-script 会将这些修改转发到主线程,并将它们应用到 amp-script 元素子树中。
例如,在 document.body中添加一个元素:
// my-script.js const p = document.createElement('p'); p.textContent