无法在Javascript之前加载HTML [英] Unable to load HTML before Javascript

查看:57
本文介绍了无法在Javascript之前加载HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,并且知道如何在执行javascript之前加载html.

I am new to Javascript, and know how can I load html before javascript is executed.

我确实检查了关于stackoverflow的问题,并尝试实施给出的解决方案,但是没有一个起作用.

I did check the questions on stackoverflow and tried to implement the solutions given but none worked.

以下是我尝试过的各种代码的代码.

Following is the code of various code that I tried.

  1. 在正文结束之前写脚本标签

  1. Wrote script tag before the body ends

在函数内部编写了javascript代码,并在body的onload内调用了该代码,但是它也不起作用. (还尝试注释documnet.onload = cal();并执行).

wrote the javascript code inside a function and called it inside onload of body but it didn't work either. (Also tried to comment documnet.onload = cal(); and execute).

<!DOCTYPE html>
<html>
<head>
<title>Age Calculator</title>

</head>
<body onload="cal();">
<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script type="text/javascript" src="Age.js"></script>
</body>
</html>

//Javascript code
function cal(){
  var age = prompt("How old are you?");
  var days = age * 365.25;
  alert("You are approx " + days + " days");
}

documnet.onload = cal();

我希望在询问用户之前显示html.

I want the html to be displayed before user is asked How old are you?

推荐答案

问题是prompt和类似的功能,例如Alert 阻止浏览器-它们会阻止呈现,直到弹出框出现已提交或取消.

The problem is that prompt and similar functions like alert block the browser - they prevent rendering until the pop-up box has been submitted or canceled.

<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script>
  var age = prompt("How old are you?");
</script>

如果要确保在prompt出现之前显示HTML,可以使用setTimeout,使浏览器有机会在调用prompt之前绘制HTML:

If you want to make sure the HTML displays before the prompt comes up, you might use setTimeout, giving the browser a chance to paint the HTML before the prompt gets called:

<h1>Age Calculator</h1>
<p>Enter your age and find how many days you have been alive</p>
<script>
  setTimeout(() => {
    var age = prompt("How old are you?");
  });
</script>

但是更好的解决方案是使用适当的模式,例如带有submit按钮的输入框,它不会阻止浏览器. (最好尽可能不要使用alertpromptconfirm)

But an even better solution would be to use a proper modal, such as an input box with a submit button, which won't block the browser. (best to never use alert, prompt, and confirm if at all possible)

这篇关于无法在Javascript之前加载HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆