运行 JavaScript 在 AMP 中

Running JavaScript in AMP

我对 AMP 页面中的 JavaScript 应该是 运行 感到有点困惑。

我了解到我的 JavaScript 必须在 iframe 中执行。这样的 iframe 必须放在页面的下方(至少从顶部算起 75%)并且必须通过 https 提供。这确实有效:

<amp-iframe 
  width=300 
  height=300 
  sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox" 
  layout="responsive"
  frameborder="0" 
  src="https://localhost:8000/?p=myjs">
</amp-iframe>

在那个页面(https://localhost:8000/?p=myjs)我可以自由运行我的js.

我的问题如下:

我应该如何 运行 我的代码针对包括 iframe 在内的主页文档?

我尝试访问 window.parent.document 但被阻止了。 (当然)。

任何人都可以解释 AMP 人员如何认为如果我们所有的 js 都被杀死,我们实际上可以将页面移植到 AMP 吗?在 AMP 页面上使用我们的 js 运行 的推荐模式是什么?有没有这样的事情,或者只是假设开发人员必须转储所有代码?

谢谢

How am I supposed to run my code against the document of the main page including the iframe?

你不是。

Can anyone explain how AMP people think we can actually port pages to AMP if all our js gets killed?

我们的想法是编写不依赖于 JavaScript 的轻量级页面。

来自the spec

AMP HTML is a subset of HTML for authoring content pages such as news articles in a way that guarantees certain baseline performance characteristics.

"Content pages such as news articles"不需要JavaScript。如果您不写那种类型的页面,那么 AMP HTML 可能不是一个好的语言选择,您应该坚持使用 HTML 5.

正如另一位评论者所说,AMP 的基本支柱之一是您不能 运行 自己的 JavaScript。我们的想法是让网页更快、更简单、更可靠。

您确实可以 运行 iframe 中的 JS,但是 JS 与主页的交互将受到很大限制。

所以使用 vue.js 这样的框架与 AMP 的观点背道而驰。

另一方面,AMP 带有各种内置的东西,不需要大多数 JS。它是一个网络组件库。通过 和 可以进行大量的动态交互和服务器通信。

在 AMP Conf 2018 上引入了对自定义 JS in AMP 使用网络工作者的支持。它应该在今年晚些时候准备就绪。

google 似乎正在推动 amp 作为新要求。人们说这是为了推出 'news' 但 google 似乎并没有推动那个方向。以下是 amp 项目关于 amp 用途的​​说明:

网页速度提高了用户体验和核心业务指标。 AMP 页面加载近乎即时,使您能够在 link 到 AMP 页面(包括 Google、Bing、LinkedIn 等)的所有设备和平台上提供始终如一的快速体验。这些性能提升通常会转化为重要数字的改进,例如花在页面上的时间、return 访问次数和点击率。

我没有看到任何关于撰写新闻文章的提及。言外之意是你需要采用它,但我不买账。它是高度限制性的并且消除了创造力。海事组织。

截至 2019 年 4 月 11 日 Official Announcement

现在您可以在 AMP 页面中包含自定义 JavaScript

AMP 页面通过 <amp-script> 组件支持自定义 JavaScript。

试用amp-script example

<!doctype html>
<html ⚡>
<head>
  ...
  <script async custom-element="amp-script" src="https://cdn.ampproject.org/v0/amp-script-0.1.js"></script>
<body>  
  ...
  <amp-script layout="container" src="https://example.com/myfile.js">
    <p>Initial content that can be modified from JavaScript</p>
  </amp-script>
  ...
</body>
</html>

只是 运行 我对这个问题的旧答案,现在已经非常过时了。

A​​MP 现在提供 <amp-script> 作为在 AMP 中的 Web Worker 中包含自定义 JavaScript 的方式。检查 documentation here. Or try this tutorial.

此外,如果有效的 AMP 对您来说不重要,欢迎您添加所有 JavaScript 您想要的内容!它只是不会通过验证。 Recent announcements in Google Search 可能会使有效的 AMP 变得不那么重要,具体取决于您的用例。