hello
hello

Reputation: 141

How to load javascript after all DOM element rendered in Vanilla javascript?

I am building SPA with only use vanilla javascript now.
At first, router check location.pathname and render HTML view that matchs the path.
This is code : document.querySelector("#app").innerHTML = await view.getHtml();

After that code, I wrote call javascript function from another module that matches current location pathname. It's for add event listener on html elements.

The problem is, it shows error : Cannot read property 'classList' of null, I think this is because of loading order. Because javascript didn't wait for all html rendered, it try to add eventlistener to null.

So I want to make javascript function called after html elements all loaded like <script defer> in html. (I can't use it, I should do it only by javascript code)

Does anybody know how to that? My current code is here...

const router = async () => {
  // check current pathname and match the view
  ...
  document.querySelector("#app").innerHTML = await view.getHtml();
  const path = location.pathname;
  if (path === "/") main();
  if (path === "/list") list();
}

document.addEventListener("DOMContentLoaded", () => {
  router();
});

Upvotes: 1

Views: 2240

Answers (1)

Sebasti&#225;n Espinosa
Sebasti&#225;n Espinosa

Reputation: 2133

You have 2 options, as Maxzeroedge commented, you can add a listener to the load event in the DOM so that block gets executed after all the elements are loaded, so you can reference all the object from your app.

The second option is simpler and is to start your app in the last line of the body, like:

<html>
  <head>
    ...
  </head>
  <body>
    // All your elements here.
    <script type="text/javascript" src="./-your-script-.js"></script> // The last line is your script call.
  </body>
</html>

This will run after all elements are declared so you don't have any reference problems.

Upvotes: 2

Related Questions