Javascript 首先执行,然后在正文中加载文本

标签 javascript html

为什么在我的浏览器中,当我首先运行我的 java 脚本文件时,它会在 body 中加载文本,但是当我在 stackoverflow javascript 片段工具中运行它时,它运行正常。

var name= prompt("enter your name");
var age= prompt("enter your age");
var pet_name= prompt("enter your fav pets name");

alert("hi "+name+" your age is "+age+"and you love"+pet_name);
console.log("hi "+name+" your age is "+age+"and you love"+pet_name);
<!DOCTYPE html>
<html>
<head>
	<title>testing javascript</title>
</head>
<body>

<h4>Testing of my first java script</h4>

<script type="text/javascript" src="test_1.js"></script>

</body>
</html>

最佳答案

我相信这是因为警报、确认和提示都是“阻塞”函数,并且在渲染发生的同时调用它们,尝试将代码放在 setTimeout 或文档准备好中:

document.addEventListener("DOMContentLoaded", function(event) { 
  // your code
});

var delayedScript = function() {
  // your code
}

setTimeout(delayedScript, 500);

https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#Notes

Dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed

关于Javascript 首先执行,然后在正文中加载文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45449145/

相关文章:

html - 如何从 float 图像中删除多余的边距底部?

javascript - 将网络摄像头视频渲染到 Canvas 时超出最大调用堆栈大小

javascript - 跨页面异步通信

javascript - 从字符串中解析数字

javascript - 如果在行中,如何从 jquery-ui 制作标签以重新排序?

javascript - 日期显示不正确

html - 向左浮动让我的盒子跳下来

javascript - Firebase 数据快照返回键但没有 .val()

文本的jquery长度()

html - 如何使用背景大小 : contain on element with responsive height