Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to load HTML before Javascript

I am new to Javascript, and know how can I load html before javascript is executed.

I did check the questions on stackoverflow and tried to implement the solutions given but none worked.

Following is the code of various code that I tried.

  1. Wrote script tag before the body ends

  2. wrote the javascript code inside a function and called it inside onload of body but it didn't work either. (Also tried to comment documnet.onload = cal(); and execute).

<!DOCTYPE html>
<html>
<head>
<title>Age Calculator</title>

</head>
<body onload="cal();">
<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script type="text/javascript" src="Age.js"></script>
</body>
</html>
//Javascript code
function cal(){
  var age = prompt("How old are you?");
  var days = age * 365.25;
  alert("You are approx " + days + " days");
}

documnet.onload = cal();

I want the html to be displayed before user is asked How old are you?

like image 812
krrish Avatar asked Dec 28 '18 04:12

krrish


1 Answers

The problem is that prompt and similar functions like alert block the browser - they prevent rendering until the pop-up box has been submitted or canceled.

<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script>
  var age = prompt("How old are you?");
</script>

If you want to make sure the HTML displays before the prompt comes up, you might use setTimeout, giving the browser a chance to paint the HTML before the prompt gets called:

<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script>
  setTimeout(() => {
    var age = prompt("How old are you?");
  });
</script>

But an even better solution would be to use a proper modal, such as an input box with a submit button, which won't block the browser. (best to never use alert, prompt, and confirm if at all possible)

like image 102
CertainPerformance Avatar answered Nov 16 '22 00:11

CertainPerformance