如何在astro JS中使用文档和窗口元素?
我想使用窗口或文档返回当前页面的路径默认 Astro.site.pathname 无法正常工作或没有正确的文档。
我的问题是如何在 Astro JS 中正确使用文档或窗口?
提前致谢!
I want to use window or document to return path of the current page default Astro.site.pathname isn't working right or proper documentation isn't available.
My question is how to use document or window properly in Astro JS?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想使用
window
或document
等内容,则需要在中编写脚本。这样 Astro 就不会接触你的 JS 并将其直接包含在 HTML 中。位于页面顶部
--- ---
之间的 JS 将在构建时执行。You need to write the script inside
<script is:inline></script>
if you want to use things likewindow
ordocument
. This way Astro won't touch your JS and include it directly on the HTML. The JS positioned on the top of the page between--- ---
will be executed at build time.您还可以使用 const { pathname } = Astro.url 从 Astro 组件访问当前路径名。
You can also access the current path name from an Astro component using
const { pathname } = Astro.url
.文档中提到的脚本标签
标签足以使用文档和窗口,因为它适用于客户端 Javascript
https://docs.astro.build/en/guides/client-side-scripts/#using-script-in -astro
内联脚本
如果您不需要
,则不建议使用它,因为它旨在避免捆绑您的脚本,而这种情况很少需要。如果您使用包含该脚本的组件,假设有 10 个实例(例如 10 张卡片),则该脚本将重复 10 次,从而导致加载性能受到影响。
https://docs.astro.build/en/guides/ client-side-scripts/#script-bundling
示例
此示例展示了如何在纯 Astro 中创建多个客户端计数器,这与纯 html 类似。请注意
document.querySelectorAll(".card")
中document
的用法,更多详细信息请参见 https://docs.astro.build/en/core-concepts/astro-components/
这里是完整示例存储库项目的链接:
https://github.com/MicroWebStacks/astro-examples#04_client-counters
和这里指向该存储库的直接 StackBlitz 项目的链接
https://stackblitz.com/github/MicroWebStacks/astro-examples/tree/main/04_client-counters
Script tag
<script>
tag as mentioned in the documentation is enough for using document and window as it is meant for client side Javascripthttps://docs.astro.build/en/guides/client-side-scripts/#using-script-in-astro
Inline Script
<script is:inline>
is not recommended if you do not need it because it's intended to avoid bundling your script, which is rarely needed. And if you use the component containing that script, in let's say 10 instances (e,g, 10 Cards), you'll have that script 10 times duplicated, so results in loading performance impact.https://docs.astro.build/en/guides/client-side-scripts/#script-bundling
Example
This example shows how to create multiple client side counters in pure Astro, which is similar to pure html. Note the usage of
document
indocument.querySelectorAll(".card")
more details in https://docs.astro.build/en/core-concepts/astro-components/
here a link to the full example repo project:
https://github.com/MicroWebStacks/astro-examples#04_client-counters
and here a link to a direct StackBlitz project pointed on that repo
https://stackblitz.com/github/MicroWebStacks/astro-examples/tree/main/04_client-counters
– Docs
您可以使用
is:inline 指令在您的
.astro
组件中如下所示:– Docs
You can use the
is:inline
directive like so in your.astro
components: