Home > Blockchain >  How can I run HTML code before JavaScript?
How can I run HTML code before JavaScript?

Time:10-28

My question might looks simple, I've searched the web with no answer. I the browser to run my <h1> HTML tag first, then go for JavaScript file. But the result is that JavaScript is blocking my HTML code and run the prompt() first. I hope you can help my find learn something new.

This is my HTML code

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Keyless Car</title>
</head>
<body>
    <h1>Hello there, this is your Keyless Car.</h1>
    <script type="text/javascript" src="Keyless car.js"></script>
</body>
</html>

This is my JavaScript code:

var age = prompt("How old are you?");

if (Number(age) < 18){
    alert("Sorry, you are too young to drive this car. Powering off");
}
else if (Number(age) === 18){
    alert("Congratulations on your first year of driving. Enjoy the ride!");
}
else{
    alert("Powering On. Enjoy the ride!");
}

I tried putting the <script> in <head>, end of the <body>, after <body> and also after </html> but the same issue is still popping up.

CodePudding user response:

Put async in the <script> tag so the browser will load it asynchronously, and it won't wait for it to finish running before rendering the page.

Example:

<script type="text/javascript" src="Keyless car.js" async></script>

CodePudding user response:

Put your javascript in a function, and then slightly delay the function:

function myFunction() {
    let age = prompt("How old are you?");

    if (Number(age) < 18){
        alert("Sorry, you are too young to drive this car. Powering off");
    }
    else if (Number(age) === 18){
        alert("Congratulations on your first year of driving. Enjoy the ride!");
    }
    else{
        alert("Powering On. Enjoy the ride!");
    }
}
setTimeout(myFunction, 50);

It's just delaying it for 50 milliseconds, which is 1/20 of a second; practically instant.
However, that is on Chrome. I have not tested it on any other browsers, but I think it should work on pretty much all browsers.

  • Related