window.onload inside of Astro js not working

Viewed 278

I have a set of Astro components to be called by my App:

apps/myProject

libs/components/header

Inside the header.astro component, I have a script that I want to be run once the entire page is rendered:

<script is:inline>
  console.log('hej!');
  window.onload = (e) => {
    console.log('loaded!');
  };
</script>

The 'hej!' is being printed but not the 'loaded!'. Why is that?

For me, it is not clear how the component's lifecycle works in Astro, and I have followed this solution by adding the is:inline property to the script tag, but it still doesn't work.

2 Answers

Think of *.astro files as all server side, you cannot use <script>...</script> inside the

---
---

but you can use <script></script> in the html part of astro file. the below example works fine for me.

---
---

<script>
    console.log('hello');
    window.onload = (e) => {
        console.log('loaded!');
    };
</script>

<p>hello world!</p>

You should be able to use load modules on the client with hoist.

<script type="module" hoist>
  console.log('loaded!');
</script>

window.onload isn't necessary since ES modules are automatically deferred.

Related