在AMP(Accelerated Mobile Pages)中,<amp-script>
元素允许你嵌入自定义的JavaScript代码,但有一些限制以确保页面性能和安全。关于在<amp-script>
中使用URL搜索参数,以下是一些基础概念和相关信息:
?
后面的部分,用于传递额外的信息。例如,在URL https://example.com/?param1=value1¶m2=value2
中,param1=value1
和 param2=value2
就是搜索参数。<amp-script>
是AMP中用于嵌入自定义JavaScript代码的元素,但它有一些限制,比如不能访问DOM,不能使用某些浏览器API等。<amp-script>
标签内编写JavaScript代码。src
属性引用外部的JavaScript文件。<amp-script>
。<amp-script>
中使用URL搜索参数?<amp-script>
本身不能直接访问DOM,因此不能直接获取URL搜索参数。
可以通过在HTML中定义一个全局变量来传递URL搜索参数,然后在<amp-script>
中使用这个变量。
<!DOCTYPE html>
<html amp lang="en">
<head>
<meta charset="utf-8">
<title>AMP Script Example</title>
<link rel="canonical" href="https://example.com/">
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "WebPage",
"name": "AMP Script Example"
}
</script>
<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>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</head>
<body>
<amp-script width="300" height="100" layout="fixed">
<script type="text/javascript">
// 获取全局变量
const params = windowSearchParams;
console.log(params);
</script>
</amp-script>
<script type="application/json" id="windowSearchParams">
{
"param1": "value1",
"param2": "value2"
}
</script>
</body>
</html>
<script type="application/json" id="windowSearchParams">
,将URL搜索参数作为JSON对象存储在这个脚本中。<amp-script>
中通过windowSearchParams
变量访问这些参数。通过这种方式,你可以在<amp-script>
中使用URL搜索参数,同时遵守AMP的限制和优化原则。
领取专属 10元无门槛券
手把手带您无忧上云