简体   繁体   English

为什么在执行Javascript文件之前未呈现H1标签?

[英]Why is the H1 tag not being rendered before the execution of a Javascript file?

I am learning Javascript and I am doing a small exercise in which I try to guess a random number within 5 attempts. 我正在学习Javascript,并且正在做一个小练习,尝试在5次尝试中猜测一个随机数。

I have defined a small HTML file in which I load the Javascript file at the end of the <body> tag. 我定义了一个小的HTML文件,在其中将Javascript文件加载到<body>标记的末尾。

 //datos del programa var numCorrect = parseInt(Math.random() * 100); //valor generado aleatoriamente console.log(numCorrect); var numAdivinado; var guesses = []; var limit = 5; //mostrando caja de texto al usuario while ( limit > 0) { limit--; numAdivinado = parseInt(window.prompt("Ingrese un número")); if (valArray(numAdivinado) == true) { limit++; } document.write("Los numeros hasta ahora ingresados son: " + guesses.toString() + "\\n"); if (numAdivinado == numCorrect) { document.write("El numero ingresado coincide con el aleatorio"); break; } else { window.alert("Error! - Le quedan " + limit + " intentos"); } if(limit == 0) { document.write("Perdio! - El número correcto era: " + numCorrect); } } //función que valida el array function valArray(numb) { if (guesses.length > 0) { for(var i = 0; i<guesses.length; i++) { if(numb == guesses[i]) { window.alert("El numero ya fue elegido, debe usar otro - no perdera una portunidad"); return true; } } guesses[guesses.length] = numb; return false; } else { guesses[0] = numb; return false; } } 
 <!DOCTYPE HTML> <html lang="es"> <head> <meta charset="utf-8"> <title>Guessing Game</title> </head> <body> <h1>Guessing Game</h1> <script src="game.js"></script> </body> </html> 

When I load the page for the first time the H1 tag is rendered and then the pop-up window that requests a number appears, which starts the execution of the application. 当我第一次加载页面时,会渲染H1标签,然后会出现一个要求输入数字的弹出窗口,从而开始执行该应用程序。 At the end of the execution of the application and show the results, I use the F5 or CTRL + F5 keys to reload the page and run the application again but I do not understand why the H1 tag is not rendered again before displaying the pop-up window. 在执行应用程序并显示结果的最后, 我使用F5CTRL + F5键重新加载页面并再次运行该应用程序,但是在显示弹出窗口时,我不明白为什么未再次渲染H1标签。上窗口。 Simply pop up the popup window directly and after all the attempts are made, everything is rendered including the H1 tag. 只需直接弹出窗口,在进行所有尝试之后,将渲染所有内容,包括H1标签。

So far I've read that when I add the <script> tag to the end of the body, I should at least allow the <H1> tag to be rendered at the first instance with the title and then execute all the JS logic. 到目前为止,我已经读到,当我在主体的末尾添加<script>标记时,我至少应允许首先在具有标题的情况下呈现<H1>标记,然后执行所有JS逻辑。

Could you explain to me why this is not happening? 您能向我解释为什么这种情况没有发生吗? or how the HTML rendering actually works in this example. 或在此示例中HTML呈现的实际工作方式。

it doesnt get rendered because you are in a while loop which doesnt leave time for the rendering if you define a function instead and call it with setTimeout(functionName,1) at the end it will work this leaves 1 millisecond etween each call where the rendering can happen example : 它不会被渲染,因为您处于while循环中,如果您定义一个函数并最后使用setTimeout(functionName,1)调用它,则不会为渲染留出时间,它将在每次调用之间留出1毫秒的时间可能发生的例子:

         limit =5;
         function parseNumber(currentLimit);
           numAdivinado = parseInt(window.prompt("Ingrese un número"));

           if (valArray(numAdivinado) == true) {
               limit++;
           }

           document.write("Los numeros hasta ahora ingresados son: " + guesses.toString() + "\n");

           if (numAdivinado == numCorrect) {
               document.write("El numero ingresado coincide con el aleatorio");
               break;
           } else {
               window.alert("Error! - Le quedan " + limit + " intentos");
           }

           if(limit == 0) {
               document.write("Perdio! - El número correcto era: " + numCorrect);
           }
           if(currentLimit<limit ){
               //functino to call , timeout, ...parameters
               setTimeout(parseNumber,1,currentLimit-1)
           }
        }
        parseNumber(0);

You can wrap your javascript with: 您可以使用以下方法包装您的JavaScript:

document.addEventListener("DOMContentLoaded", function() {
   // your page initialization code here
   // the DOM will be available here
});

this will ensure that your DOM has loaded before your script executes. 这样可以确保脚本执行之前已加载DOM。


Also, you should not use document.write as @Alex Kudryashev mentioned. 另外,您不应使用@Alex Kudryashev提到的document.write。 You should use document fragments using document.createElement, and appendChild: 您应该使用document.createElement和appendChild来使用文档片段:

let paragraph = document.createElement('p');
paragraph.innerText = "whatever I need to load or say";

// you can use the body, a div, or whatever element you want to append to
myElement.appendChild(paragraph);

jsPerf CoderWall Article jsPerf CoderWall文章

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

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