简体   繁体   English

如何在加载其他页面元素后加载 javascript?

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

So I made this rock-paper-scissors game in HTML.所以我用 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.问题是在我的任何 div 之前加载弹出窗口,我希望我的所有 html 元素在弹出脚本启动之前都可见。

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您的 javascript 在页面的其余部分加载之前执行

You are trying to use window.onload , but you are doing it wrong.您正在尝试使用window.onload ,但您做错了。 window.onload should be a function, like this: window.onload应该是一个函数,像这样:

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.一般来说,最好使用 window.addEventListener 方法,因为您可以使用其中的多个方法,并且所有方法都将被执行。

If you would use another window.onload = function(){} , it would override the first one.如果您使用另一个window.onload = function(){} ,它将覆盖第一个。

That's why I recomment using:这就是为什么我建议使用:

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

Solution 1:解决方案1:

You could put your script at the bottom of the HTML document.您可以将脚本放在 HTML 文档的底部。 This will run your code after the <div> elements have loaded:这将在<div>元素加载后运行您的代码:

<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:解决方案 2:此外,您可以将所有 JS 放在window.onload事件侦听器中:

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.在 html 页面中的结束正文标记之前添加您的脚本标记。
  2. Call your logic as part of your body onload event调用您的逻辑作为您的身体 onload 事件的一部分

    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:如果您使用的是 jquery,您可以通过执行以下操作获得与上述相同的结果:

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

Hero1134 is totally right if you use jQuery.如果您使用 jQuery,Hero1134 是完全正确的。 If you're using jQuery though you should probably use如果你使用 jQuery,虽然你应该使用

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

The .ready function will execute as soon as the DOM is ready (html elements loaded and ready to be worked against). .ready 函数将在 DOM 准备好(加载 html 元素并准备好对其进行处理)后立即执行。 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.如果您使用 .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如果您只想使用没有依赖项的普通旧 javascript 并且您想在文件顶部包含 js,则可以修复此行

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你有两个选择 1.在 JavaScript 中,你可以像下面的语法那样做

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

2.In Jquery do like this 2.在Jquery中这样做

$(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.您可以在执行 JavaScript 之前使用 JQuery 加载 HTML 页面。 Something similar to this could work.类似的东西可以工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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