请帮助我了解如何在AMP(加速移动页面)中添加javascript。我的要求是我在URL中获取ID。例如localhost:8080 / home?id = 1.我想在我的html文件中访问该id。
或者请告诉我如何添加任何javascript文件。
谢谢。
答案 0 :(得分:7)
不幸的是,您无法在AMP中添加任意脚本。来自the specification的“HTML代码”下的代码script
:
禁止,除非类型为
application/ld+json
。 (可以根据需要添加其他非可执行值。)例外是加载AMP运行时的必需脚本标记和加载扩展组件的脚本标记。
因此,如果您想使用AMP中的JavaScript,则必须使用AMP的预定义components。我没有看到一个能够满足你想要的组件。
答案 1 :(得分:3)
据我所知,您可以通过在您的源上托管AMP脚本来添加Javascript到AMP,并拦截使用Service Worker获取脚本的请求。该技术称为“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
答案 2 :(得分:1)
Javascript阻止DOM构建并延迟页面呈现,因此AMP只允许异步Javascript - AMP页面不能包含任何自定义Javascript。可以在自定义AMP元素中处理交互式页面功能,而不是使用Javascript。
答案 3 :(得分:1)
截至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>
html
组件将amp-script
元素包裹起来:<!-- 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
答案 4 :(得分:0)
AMP页面上不允许使用自定义JavaScript,这是AMP的基本原则之一。您可以将自定义j放在amp-iframe中,只要amp-iframe是主页面的xdomain'd即可。