Programming Elm: need to wait for DOMContentLoaded to getElementById?

When we first create picshare.js we’re told to link it from our HTML with

<script>
Elm.Picshare.init({node: document.getElementById('main')});
</script>

but when I try this it looks like the getElementById doesn’t find anything (I’ve got the script in my head node).
When I wrap it in a document.addEventListener('DOMContentLoaded', (event) => {Elm.Picshare.init ... things work OK.
Was I doing something wrong?

2 Likes

Hi, @gcapell!

Thanks for the question and sorry for missing your question so long ago. We’ve been transitioning over with the new Prag site changes to these forums.

You can definitely place the script tags in the head if you like and then use the DOMContentLoaded event to kick off the initialization as you’ve already done.

The intent in the book was to place the script before the closing </body> tag, replacing the <!-- REPLACE ME --> comment. As long as the script tags are below the <div id="main"> tag, you don’t need the DOMContentLoaded event as that element will be available by that point. I can see how the book could be misleading, though, since it doesn’t explicitly say to put the scripts in the body.

Sorry for the confusion and glad you had figured out a way to fix it with the event.

Cheers!

2 Likes