I’m using API calls through JavaScript to check if a user is logged in or not, and replace the logout element
in case the API returned an Ok response. However, the HTML document load first, and the API call takes time, which creates a delay, and even if the user is logged in, the login element
will show up for half a second and then disappear
if you run the below code multiple times, you will see the login element
show up for half a second. How do I fix this?
login_status();
function login_status() {
fetch("https://jsonplaceholder.typicode.com/todos/1", {
method: "GET",
}).then(function(response) {
if(response.ok) {
document.getElementById("login").style.visibility = "hidden";
document.getElementById("logout").style.visibility = "visible";
}
});
}
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover:not(.active) {
background-color: #111;
}
.active {
background-color: #04AA6D;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact" id="login">Log In</a></li>
<li><a href="#contact" id="logout" hidden>Log out</a></li>
<li style="float:right"><a class="active" href="#about">About</a></li>
</ul>
<div id="output">
</div>
</body>
</html>