【问题标题】:Add Javascript in AMP Pages在 AMP 页面中添加 Javascript
【发布时间】:2017-05-02 23:11:40
【问题描述】:

请帮助我了解如何在 AMP(加速移动页面)中添加 javascript。我的要求是我在 URL 中获得一个 ID。例如 localhost:8080/home?id=1。我想在我的 html 文件中访问该 id。

否则请告诉我如何添加任何 javascript 文件。

谢谢。

【问题讨论】:

标签: javascript amp-html


【解决方案1】:

很遗憾,您不能在 AMP 中添加任意脚本。来自the specification,在“HTML 标签”下,标签script

除非类型是application/ld+json,否则禁止。 (可以根据需要添加其他不可执行的值。)例外是加载 AMP 运行时的强制脚本标记和加载扩展组件的脚本标记。

因此,如果您想使用 AMP 中的 JavaScript,则必须使用 AMP 的预定义components。我没有看到可以满足您需求的组件。

【讨论】:

  • 我们可以使用
【解决方案2】:

截至 2019 年 4 月 11 日Official Announcement

现在可以在带有 amp-script 组件的 AMP 项目中使用您的 JS。

首先你需要将它导入到你的项目中:

  1. .html 文件导入的顶部:
<script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>
  1. 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>
  1. 现在可以创建 JS 文件了
// 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

【讨论】:

  • 这是实验性的,还不能用于生产!
  • @Exlord 我很确定我正在使用它.. 你能备份一下吗?也许我错过了什么
  • 你能分享一个简单的可用html吗?对我来说,它在控制台中说我没有实验令牌或其他东西!据我所知,令牌已绑定到域,并且我的小部件是 gana 用于客户站点,他们需要自己获取令牌,并且我的雇主无法接受
  • cookie 的东西在 amp-script 中也不起作用
【解决方案3】:

据我所知,您可以通过在您的源上托管 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

【讨论】:

  • 这是一个不错的解决方案,但不幸的是,iOS safari 尚不支持 Service Worker:caniuse.com/#feat=serviceworkers(通常如果您创建 AMP 页面,是针对移动平台的,对吧?)
【解决方案4】:

Javascript 会阻止 DOM 构建并延迟页面呈现,因此 AMP 仅允许异步 Javascript - AMP 页面不能包含任何自定义 Javascript。交互式页面功能可以在自定义 AMP 元素中处理,而不是使用 Javascript。

【讨论】:

    【解决方案5】:

    AMP 页面上不允许使用自定义 javascript,这是 AMP 的基本原则之一。您可以将自定义 js 放在 amp-iframe 中,只要 amp-iframe 是来自主页的 xdomain'd。

    【讨论】:

    • 仅供参考,您可以通过提供支持您声明的来源来使这个答案变得更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多