简体   繁体   中英

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();
});

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.

First of all, thanks to everyone who left answers.
Thinking of what you guys said, I fix it by create script tag, and append it. Below solution works well, but I'm still wondering if there is a better way.
Anyway, thanks again to everyone who tried to help!

  const path = location.pathname;
  if (path === "/") {
    const script = document.createElement("script");
    script.src = "./js/script.js";
    script.type = "module";
    document.body.appendChild(script);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM