DOMContentLoaded Gotcha

Just wanted to share a little gotcha that was breaking some custom html that I was using. I was using the DOMContentLoaded event in a form’s custom html to trigger the setup for an animation like this:

<script>
  document.addEventListener("DOMContentLoaded", () => {
    testFn();
  });
</script>

Testing this in a page outside of Anvil and everything worked great. Throw the html into a form and nothing worked. I couldn’t get the DOMContentLoaded event to fire. click, resize events work fine.

The issue is that HTML in the form has already missed the event, so it never triggers. I think if you are ever trying to replicate some JS in a Anvil form, you can just assume that the DOMContentLoaded has fired and just jump right to running the code that was wrapped in the event handler. Our example above just becomes:

<script>
  testFn();
</script>

However, if you want to have code work inside and outside of Anvil here is what I found to work:

<script>
  if (document.readyState !== 'loading') {
    console.log("Missed `DOMContentLoaded` event");
      testFn();
    }
    else {
      document.addEventListener("DOMContentLoaded", () => {
        testFn();
      });
    }
</script>

Seemed like there were a few people that were running into this issue so I thought I would give a more direct answer for future Anvil users.

Here is a complete example:

2 Likes