External javascript file not working in HTML file

I’m trying to change the property of a div from a javascript file but it’s not working, it’s working if I put it inside body but I want to work it from external js file for some project.

HTML file

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Calendar</title>
    <link rel="stylesheet" href="css/styles.css">
    <script src="javascript/cal.js"></script>
  </head>
  <body>

    <div id="container">

      <div id="calendar-view">

      </div>

      <div id="events-view">

      </div>

    </div>


  </body>
</html>

CSS file

*{
  box-sizing: border-box;
}

#calendar-view{
  float: left;
  width: 70%;
  background-color: blue;
  height: 200px;
}

#events-view{
  float: left;
  width: 30%;
  height: 200px;
  background-color: red;
}

#container::after{
  content: "";
  clear: both;
  display: table;
}

Javascript file

function startUp(){
  document.getElementById("calendar-view").style.display = "none";
}

startUp();

I’m trying to change the property of a div from a javascript file but it’s not working, it’s working if I put it inside body but I want to work it from external js file for some project.

Answer

When you import your JS file at your JS loads and then your body.

When you import your JS file after your body loads and then your JS.

The first solution is to put your JS file after the second one is to put the function call inside the window onload event listener