【发布时间】:2017-05-02 23:11:40
【问题描述】:
请帮助我了解如何在 AMP(加速移动页面)中添加 javascript。我的要求是我在 URL 中获得一个 ID。例如 localhost:8080/home?id=1。我想在我的 html 文件中访问该 id。
否则请告诉我如何添加任何 javascript 文件。
谢谢。
【问题讨论】:
标签: javascript amp-html
请帮助我了解如何在 AMP(加速移动页面)中添加 javascript。我的要求是我在 URL 中获得一个 ID。例如 localhost:8080/home?id=1。我想在我的 html 文件中访问该 id。
否则请告诉我如何添加任何 javascript 文件。
谢谢。
【问题讨论】:
标签: javascript amp-html
很遗憾,您不能在 AMP 中添加任意脚本。来自the specification,在“HTML 标签”下,标签script:
除非类型是
application/ld+json,否则禁止。 (可以根据需要添加其他不可执行的值。)例外是加载 AMP 运行时的强制脚本标记和加载扩展组件的脚本标记。
因此,如果您想使用 AMP 中的 JavaScript,则必须使用 AMP 的预定义components。我没有看到可以满足您需求的组件。
【讨论】:
截至 2019 年 4 月 11 日Official Announcement,
现在可以在带有 amp-script 组件的 AMP 项目中使用您的 JS。
首先你需要将它导入到你的项目中:
.html 文件导入的顶部:<script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>
amp-script 组件包装html 元素:<!-- hello-world.html -->
<amp-script layout="container" src="https://yourdomain.com/hello-world.js">
<button id="hello">Insert Hello World!</button>
</amp-script>
// hello-world.js
const button = document.getElementById('hello');
button.addEventListener('click', () => {
const el = document.createElement('h1');
el.textContent = 'Hello World!';
// `document.body` is effectively the <amp-script> element.
document.body.appendChild(el);
});
您可以在 AMP git repo amp-script.md
【讨论】:
据我所知,您可以通过在您的源上托管 AMP 脚本并拦截请求以使用 Service Worker 获取脚本来将 Javascript 添加到 AMP。这种技术被称为“AMP as PWA”。这是代码
function createCompleteResponse (header, body) {
return Promise.all([
header.text(),
getTemplate(RANDOM STUFF AMP DOESN’T LIKE),
body.text()
]).then(html => {
return new Response(html[0] + html[1] + html[2], {
headers: {
'Content-Type': 'text/html'
}
});
});
}
更多解释在这里:https://www.smashingmagazine.com/2016/12/progressive-web-amps/#amp-as-pwa
【讨论】:
Javascript 会阻止 DOM 构建并延迟页面呈现,因此 AMP 仅允许异步 Javascript - AMP 页面不能包含任何自定义 Javascript。交互式页面功能可以在自定义 AMP 元素中处理,而不是使用 Javascript。
【讨论】:
AMP 页面上不允许使用自定义 javascript,这是 AMP 的基本原则之一。您可以将自定义 js 放在 amp-iframe 中,只要 amp-iframe 是来自主页的 xdomain'd。
【讨论】: