Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alert is executing before html loads

Hello my questions is about how a webpage is loaded! Here is my code:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title> 
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
    alert("Why?");
</script>
</body>
</html>

I cannot for the life of me figure out why the alert is running before the heading is displayed. It is my understanding that since the alert is right above the closing body tag it will be the last thing run. Why is the page waiting for me to close out the alert before displaying the heading?

Thanks for the help!

Edit: I ran this code in firefox rather than chrome and it worked how I wanted it to - the heading displayed first before the alert ran.

like image 858
DougL Avatar asked Jul 28 '18 18:07

DougL


2 Answers

You need to execute your script after the page loads with

<body onload="script();">

An external script will execute before the page loads.

<body onload="script();">

<h1>Waiting</h1>
<script type="text/javascript">
   function script() {alert("Why?");}
</script>
</body>
like image 146
Melchia Avatar answered Nov 11 '22 16:11

Melchia


You can use setTimeout() to show the alert after a few seconds (when the page should have loaded).

<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title> 
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
setTimeout(function(){
    alert("Why?");
}, 1000);//wait 1000 milliseconds
</script>
</body>
</html>

You can check if the header (the h1 tag) is there and only alert if it is there.

<!DOCTYPE html>
    <html>
    <head>
    <title>JavaScript</title> 
    </head>
    <body>
    <h1 id="header">Waiting</h1>
    <script type="text/javascript">
    var x;
    x = setInterval(function(){
        if(document.getElementById("header")){
        alert("Why?");
        clearInterval(x);
        }
    }, 100);
    </script>
    </body>
    </html>
like image 36
Unmitigated Avatar answered Nov 11 '22 16:11

Unmitigated