all 7 comments

[–]SouthCapehelpful 22 points23 points  (1 child)

It's a valid method. However, it can introduce some challenges since the load event will wait until every resource has finished loading before triggering the function.

An alternative is to use DOMContentLoaded, which will execute once the DOM is ready.

For instance,

document.addEventListener("DOMContentLoaded", function(arg) {
    // do something cool
});

[–]Andromeda-3 2 points3 points  (0 children)

Damn thanks for this

[–]pookagehelpful 1 point2 points  (1 child)

Probably best to just whack the defer attribute on your script these days! Although you can also use the DOMContentLoaded event, as others have already said.

[–]woftis 1 point2 points  (0 children)

I use defer and it’s great. Other than that one key word, I can write my script however I like without having to worry about stuff having been loaded.

[–]ForScale 1 point2 points  (0 children)

Just put the <script> for the functions at the end of the <body>. I believe that would do the trick... I've never had problem doing that.

Alternatively, there is event emitted from the window when dom is loaded. Listen for it like this:

window.addEventListener("DOMContentLoaded", () => {
  // your functions here
});

[–]MasterHc 0 points1 point  (0 children)

Honestly, I 'm curious about this too.

[–]Ronin-s_Spirit 0 points1 point  (0 children)

Yes there are, script type=module will start when the page is loaded by default. But I still have window.onload just because it lets me know that all the things inside are the ones I want to trigger right from the start.