加速移动页面 (AMP) 对我来说非常有吸引力,因为它们的加载速度。
大规模运行付费流量时,立即加载的着陆页可以使您的投资返回率翻倍。
我正在为电子商务产品创建自定义登录页面。该页面将有:
- 顶部的导航链接可以通过单击按钮来显示或隐藏
- 调查界面,询问用户问题并相应地显示信息
- 根据某些按钮的点击,执行某些操作。例如触发 FB 广告像素事件
- 使用 jquery 滚动允许用户导航到单个页面中的每个部分
我习惯将 Jquery 包含在 <head>
中并将我的所有代码写在一个部分中。这将在 DOM 加载时加载......并且一切正常。快乐的时光。
但是,阅读有关“在 AMP 页面中包含自定义 JavaScript”的文档感觉会变得非常困难。根据我所看到的,几乎不可能。
请参见此处: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>
中包含这个库标签,这意味着我实际上不能使用多个标签?
我可以将整个 body 包含在这个<amp-script>
中吗?标签?
这是否意味着我必须有一个 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.
祝你好运!
关于javascript - 将 Jquery 添加到 AMP 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58586823/