将 Jquery 添加到 AMP 页面

Adding Jquery To AMP Pages

加速移动页面 (AMP) 因其加载速度而对我很有吸引力。

当 运行 大规模付费流量时,立即加载的着陆页可以使您的投资回报率翻倍。

我正在为电子商务产品创建自定义登录页面。此页面将包含:

我习惯于在 <head> 中包含 Jquery 并将我的所有代码写在一个部分中。这将在 DOM 加载时加载...并且一切正常。快乐的时光。

不过看了"Include custom JavaScript in AMP pages"上的文档感觉会很吃力。根据我所看到的,几乎不可能。

看这里:https://amp.dev/documentation/guides-and-tutorials/develop/custom-javascript/

看来我必须为每个自定义JS创建一个标签。使用 "src" 属性链接到我的 JS 文件。但是,只有此标记内的代码才能被 JS 文件执行。

该文档还指出,

AMP enforces a limit of 150 kilobytes of custom JavaScript on each page. This limit is shared among all component on that page. If using a library, it must be imported to each individual component.

Jquery 大约是 100 KB...如果我必须将这个库包含在每个 <amp-script> 标签中,这意味着我实际上不能使用多个标签?

我可以在此 <amp-script> 标签中包含整个 body 吗?

这是否意味着我必须有一个 JS 文件,我必须在其中复制 Jquery 库。然后在该文件中也包含我的自定义代码?

据我了解文档,您可以在需要自定义 js 的地方包裹该区域。如果您的所有页面都需要该脚本,只需将所有内容都用 amp-script 标记包裹起来。 - 我自己从未做过,但这似乎值得一试。我很想知道它是否有效。

<body>
  <amp-script layout="container" src=".../script.js">
    ...
  </amp-script>
</body>

考虑

The DOM inside tags should be almost identical before and after initialization.

If your amp-script logic is not preforming a fetch, the DOM has less than one second to update the DOM. If a script mutates the DOM outside of the permitted window, it will result in a fatal error and the amp-script component will terminate the Web Worker. A terminated component will not run again.

祝你好运!