Google AMP - 自定义 Javascript
在前面的章节中,我们研究了许多 amp 组件。我们还看到,要使每个组件正常工作,我们需要添加一个 javascript 文件。
例如,对于 amp-iframe,添加的脚本如下 −
<script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"> </script>
我们在脚本标签中添加了 async。这是 amp 的标准,因为它们异步加载所有 javascript 文件。添加了 custom-element 属性,该属性具有所用组件的名称。
要使用任何 amp-component(如果它不是核心 amp javascript 文件的一部分),必须添加脚本,如上所示。
我们主要习惯于在页面内编写大量 javascript 代码,并使用脚本标记包含 javascript 文件。
我们如何在 amp 中做到这一点?因此,AMP 不允许编写任何脚本代码或从外部加载脚本标记。
Amp 有自己的组件来处理应该由页面上添加的附加脚本完成的工作。这样做主要是出于性能方面的考虑,以便更快地加载页面内容,而不会让 javascript 延迟渲染或对 DOM 进行任何更改。
这是 AMP 在其官方网站中针对脚本标记 −
给出的规范除非类型为 application/ld+json,否则禁止使用。(可以根据需要添加其他不可执行的值。)例外情况是加载 AMP 运行时的必需脚本标记和加载扩展组件的脚本标记。
此处显示了一个我们可以在 amp 页面中使用 application/ld+json 的工作示例。请注意,我们使用 type="application/ld+json" 的脚本标记来为 amp-analytics 组件触发跟踪器。
同样,我们可以根据需要在其他 amp-components 上使用 type="application/ld+json" 的脚本标记。
示例
<!doctype html> <html amp> <head> <meta charset = "utf-8"> <title>amp-analytics</title> <script async src = "https://cdn.ampproject.org/v0.js"> </script> <script async custom-element = "amp-analytics" src = "https://cdn.ampproject.org/v0/amp-analytics-0.1.js"> </script> <link rel = "canonical" href = "ampanalytics.html"> <meta name = "viewport" content = "width=device-width, minimum-scale = 1,initial-scale = 1"> <style amp-boilerplate> body{ -webkit-animation: -amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation: -amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation: -amp-start 8s steps(1,end) 0s 1 normal both;animation: -amp-start 8s steps(1,end) 0s 1 normal both } @-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}} </style> <noscript> <style amp-boilerplate> body{ -webkit-animation:none; -moz-animation:none; -ms-animation:none; animation:none} </style> </noscript> </head> <body> <h1>Google Amp - Analytics</h1> <amp-analytics> <script type = "application/json"> { "requests": { "event": "http://localhost:8080/googleamp/tracking.php? user=test&account=localhost&event=${eventId}" }, "triggers": { "trackPageview": { "on": "visible", "request": "event", "vars": { "eventId": "pageview" } } } } </script> </amp-analytics> </body> </html>
当浏览器点击页面时,跟踪器将针对页面浏览量触发。可以在 Google 网络标签中看到它,如下所示。
