fireship-io / flamethrower

A blazingly fast router for static sites
MIT License
2.79k stars 109 forks source link

<script type="module"> is not re-run when replacing the body #88

Closed ainaracatgirl closed 1 year ago

ainaracatgirl commented 1 year ago

This library is actually very useful to me because it makes my static site smoother and allows me to use page transitions. However, I usually write the small logic islands with JavaScript using ES modules.

  <header>
    <h2>User Portal</h2>
  </header>

  <script type="module" src="/js/portal.js"></script>

This snippet will run the code in /js/portal.js (console.log("portal")) once when the page is loaded for the first time, but not when navigating out and into it again.

  <header>
    <h2>User Portal</h2>
  </header>

  <script src="/js/portal.js"></script>

This snippet, on the other hand, doesn't have this issue and shows the "portal" output in the console each time I navigate out and into it again.

I hope this is a simple fix and I'll be waiting for a response! Love your videos, Ainara.

ainaracatgirl commented 1 year ago

On a deeper look, this does seem to be a limitation of how the browser loads and runs ES Modules.

async function init() {
  console.log('portal')
}
init()

window.addEventListener('flamethrower:router:end', () => {
  // could be a one-liner, expanded for clarity
  const isPortal = location.pathname.endsWith('/portal') || location.pathname.endsWith('/portal/')
  if (isPortal) {
    init()
  }
})

This solution works for my use case. Sorry for troubling you.