简体   繁体   中英

How to make a javascript load after other page elements are loaded?

So I made this rock-paper-scissors game in HTML. when the page loads, it asks the user for their input through a pop-up. The problem is the popup loads before any of my divs and I want all my html elements to be visible before the popup script starts.

Here is my code:

<body>
    <div class="user">
        <div class="container">You choose:</div>
        <div id="userInput"></div>
    </div>
    <div class="computer">
        <div class="container">Computer chooses:</div>
        <div id="computerInput"></div>
    </div>
    <div class="results">
        <div class="container">Results:</div>
        <div id="resultsOutput"></div>
    </div>

    <script type="text/javascript">
            var userInput = prompt("Do you choose rock, paper or scissors?");
        var computerChoice = Math.random();
        if (userInput === "rock" || userInput === "paper" || userInput === "scissors") {
            var userChoice = userInput
        } else {
            userChoice = "Invalid entry, sorry. "
        }

        if (computerChoice < 0.34) {
            computerChoice = "rock";
        } else if (computerChoice <= 0.67) {
            computerChoice = "paper";
        } else {
            computerChoice = "scissors";
        }
        console.log("Computer: " + computerChoice);

        function compare(choice1, choice2) {
            if (userInput === "rock" || userInput === "paper" || userInput === "scissors") {
                if (choice1 === choice2) {
                    return "The result is a tie!";
                } else if (choice1 === "rock") {
                    if (choice2 === "scissors") {
                        return "rock wins";
                    } else {
                        return "paper wins"
                    }
                } else if (choice1 === "paper") {
                    if (choice2 === "rock") {
                        return "paper wins";
                    } else {
                        return "scissors wins";
                    }
                } else if (choice1 === "scissors") {
                    if (choice2 === "rock") {
                        return "rock wins";
                    } else {
                        return "scissors wins"
                    }
                }
            } else {
                return "Results not calculated."
            }
        }
        document.getElementById("userInput").innerHTML = userChoice;
        document.getElementById("computerInput").innerHTML = computerChoice
        compare(userChoice, computerChoice);
        document.getElementById("resultsOutput").innerHTML = compare(userChoice, computerChoice)

    </script>
</body>

Your javascript is executed before the rest of the page has been loaded

You are trying to use window.onload , but you are doing it wrong. window.onload should be a function, like this:

window.onload = function(){
    //your code here
}

But this only works if you only have ONE function you want to start on page load. In general it's better to use the window.addEventListener method, since you can use multiple of those and all will be executed.

If you would use another window.onload = function(){} , it would override the first one.

That's why I recomment using:

window.addEventListener('load',function(){
    //your code here
})

Solution 1:

You could put your script at the bottom of the HTML document. This will run your code after the <div> elements have loaded:

<html>
<head></head>
<body>
    <div></div>
    <div></div>
    <div></div>
    ...
    <script>
        // Put your JS code here
    </script>
</body>
</html>
</html>

Solution 2: Additionally, you could put all your JS inside the window.onload event listener:

window.onload = function() {
    // Put your JS code here
};

You can do three things.

  1. Add your script tag just before your closing body tag in your html page.
  2. Call your logic as part of your body onload event

    document.body.onload = function() { console.log('I loaded!'); };

  3. If you are using jquery, you can get the same result as above by doing the following:

    $(function() { console.log('I loaded!'); })(jQuery);

Hero1134 is totally right if you use jQuery. If you're using jQuery though you should probably use

$(document).ready(function(){ })

The .ready function will execute as soon as the DOM is ready (html elements loaded and ready to be worked against). If you use .load you'll wait for every element on the page to load in its entirety so you'll have to wait for large images to wait to load. On some pages the difference between these two methods can be seconds!

You can also run your script at the end of the file instead

<body>
  <divs />
  <script>var userInput = prompt("Do you choose rock, paper or scissors?"); ...</script>
</body>

So the elements will be available to the script.

If you want to just use Plain Old javascript without dependencies and you'd like to include the js at the top of the file you can fix this line

window.onload = var userInput = prompt("Do you choose rock, paper or scissors?"); ...

To be this instead

window.onload = function(){ var userInput = prompt("Do you choose rock, paper or scissors?"); ... }

You have two choices 1.In JavaScript you can do it like below syntax

document.addEventListener('DOMContentLoaded', function() {
   // your code here
}, false);

2.In Jquery do like this

$(document).ready(function(){
// your code here
});

Maybe you can try this...

<div id="quiz">
    <div class="user ">
        <div class="container">You choose:</div>
        <div id="userInput"></div>
    </div>
    <div class="computer">
        <div class="container">Computer chooses:</div>
        <div id="computerInput"></div>
    </div>
    <div class="results">
        <div class="container">Results:</div>
        <div id="resultsOutput"></div>
    </div>
</div>

<script type="text/javascript">


    window.onload = function(){

        if( document.getElementById('quiz') ){

            var userInput = prompt("Do you choose rock, paper or scissors?");
            var computerChoice = Math.random();
            if (userInput === "rock" || userInput === "paper" || userInput === "scissors") {
                var userChoice = userInput
            } else {
                userChoice = "Invalid entry, sorry. "
            }

            if (computerChoice < 0.34) {
                computerChoice = "rock";
            } else if (computerChoice <= 0.67) {
                computerChoice = "paper";
            } else {
                computerChoice = "scissors";
            }

            console.log("Computer: " + computerChoice);
            document.getElementById("computerInput").innerHTML = computerChoice;
            if( userChoice !== undefined ){
                 document.getElementById("userInput").innerHTML = userChoice;
                 compare(userChoice, computerChoice);
                 document.getElementById("resultsOutput").innerHTML = compare(userChoice, computerChoice)
            }

        }

    }


    function compare(choice1, choice2) {

        if (userInput === "rock" || userInput === "paper" || userInput === "scissors") {
            if (choice1 === choice2) {
                return "The result is a tie!";
            } else if (choice1 === "rock") {
                if (choice2 === "scissors") {
                    return "rock wins";
                } else {
                    return "paper wins"
                }
            } else if (choice1 === "paper") {
                if (choice2 === "rock") {
                    return "paper wins";
                } else {
                    return "scissors wins";
                }
            } else if (choice1 === "scissors") {
                if (choice2 === "rock") {
                    return "rock wins";
                } else {
                    return "scissors wins"
                }
            }
        } else {
            return "Results not calculated."
        }
    }


</script>

Use the function

 $(window).load(function () {

});

You could use JQuery to load your HTML page before executing your JavaScript. Something similar to this could work.

$(document).ready(init);
function init(){
 //your JavaScript code here 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM