[英]Add Javascript in AMP Pages
請幫助我了解如何在AMP(加速移動頁面)中添加javascript。 我的要求是我在URL中獲取ID。 例如localhost:8080 / home?id = 1.我想在我的html文件中訪問該id。
或者請讓我知道如何添加任何JavaScript文件。
謝謝。
據我所知,您可以通過在您的源上托管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
Javascript阻止DOM構建並延遲頁面呈現,因此AMP只允許異步Javascript - AMP頁面不能包含任何自定義Javascript。 可以在自定義AMP元素中處理交互式頁面功能,而不是使用Javascript。
截至2019年4月11日官方公告 ,
現在可以在帶有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頁面不允許使用自定義JavaScript,這是AMP的基本原則之一。 您可以將自定義j放在amp-iframe中,只要amp-iframe是主頁面的xdomain'd即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.