Invoke javascript function upon HTML element on page load

This is a beginner question. I just cannot figure out the answer as simple as it may be.

I have two files: One with a JavaScript function and the other with the HTML code. The JavaScript should build the elements of a menu.

This is what I have:

JavaScript (mynaivesdk.js):

async function buildMenu(element){

    const webElements = [{"name": "Home", "href": "index.html"}, {"name": "Works", "href": "works.html"}, {"name": "Contact", "href": "contact.html"}]
    var menu = document.getElementById(element);
    
    webElements.forEach((webelement) => {
        const row = '<li><a href="' + webelement.href + '">' + webelement.name + '</a></li>';
        menu.innerHTML += row;
    });
}

HTML:

<html>
<head>
    <script type="module" src="mynaivesdk.js"></script>
    <title>My Menu</title>
</head>
<body>
    <h1>This is my menu</h1>    
    <ul id="mymenu" onload="buildMenu('mymenu')">        
    </ul>    
   
</body>
</html>

The result is that nothing is displayed. There is no error. I am concluding my HTML is not invoking the JavaScript function at all.

This is what I would expect to have:

<html>
<head>
    <script type="module" src="mynaivesdk.js"></script>
    <title>My Menu</title>
</head>
<body>
    <h1>This is my menu</h1>    
    <ul id="mymenu">
        <li><a href=ïndex.html">Home</a></li>
        <li><a href=works.html">Works</a></li>
       <li><a href=contact.html">Contact</a></li>      
    </ul>    
   
</body>
</html>

I know this should be extremely simple. I just cannot figure out the correct way of doing this.

Thank you!

Answer

Call your function when the JS file loads and it will build your menu for you.

You’ll need to add the defer attribute to your <script> tag. This simple attribute replaces the need to do the DOMContentLoaded thing.

Here you go:

function buildMenu(menu) {

  const webElements = [{
    "name": "Home",
    "href": "index.html"
  }, {
    "name": "Works",
    "href": "works.html"
  }, {
    "name": "Contact",
    "href": "contact.html"
  }]

  webElements.forEach((webelement) => {
    const row = '<li><a href="' + webelement.href + '">' + webelement.name + '</a></li>';
    menu.innerHTML += row;
  });
}

buildMenu(document.getElementById('mymenu'));
<html>

<head>
  <script defer type="module" src="mynaivesdk.js"></script>
  <title>My Menu</title>
</head>

<body>
  <h1>This is my menu</h1>
  <ul id="mymenu">
  </ul>

</body>

</html>