I want to verify the user credentials before any page of my site load, so I put an script in the top of each of my HTML document. But this script in particularly has Async functions (because it sends API calls for the verification), and I noticed that other elements load before this script when some Async function has to be done (inside of this particularly script), even I putting at the top of the HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap" rel="stylesheet">
<link href="home.css" rel="stylesheet">
<script src="../isUserLogged.js"></script> <!--This is the script that I mentioned-->
<script src="home.js" defer></script> <!--This script is running before even with "DEFER" annotation-->
<title>Caderneta</title>
</head>
<body>
<div class="header">
<p id="home-txt" class="header-txt">Home</p>
<p id="user-txt" class="header-txt">Olá, Nome!</p>
</div>
<div class="content">
<iframe src="../notebooks/notebooks.html"></iframe>
</div>
</body>
</html>
"isUserLogged.js":
//Local Storage
const token = localStorage.getItem("token");
async function isUserSessionValid() {
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": token
},
body: token
};
try {
const response = await fetch("http://localhost:8080/teachers/get-by-token", options);
if(response.ok) {
sessionStorage.setItem("user", JSON.stringify(await response.json()));
return true;
}
} catch(e) {
}
alert("Erro ao validar sessão, faça login ou tente novamente mais tarde.");
return false;
}
async function validateUserSession() {
if(token != null) {
if(await isUserSessionValid()) {
return;
}
}
localStorage.clear();
sessionStorage.clear();
location.replace("../login/login.html");
}
validateUserSession();
What can I do to the elements just load after all async functions has fineshed?
According to the documentation the script with the
deferattribute will be executed after parsing the document but NOT after rendering the document. The reason, why you feel like the script executed before is a Rendering Delay.As
@Philmentioned in the comment, You have to do some workarounds like Adding a loading screen and hiding it when your function execution is completed.