html - JavaScript 脚本加载顺序
问题描述
但在以下情况下,即使 JavaScript 位于 html 文件的底部,它首先下载并解析,然后显示 HTML,我有点困惑 -
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Loader Sequence</title>
<link rel="stylesheet" type="text/css" href="style/style1.css">
</head>
<body>
<p>HTML parse and render</p>
<img style="max-width: 70%; height: auto; border: 1px solid red;" src="https://i.stack.imgur.com/wfL82.png">
<p>
There ain't no grave can hold my body down
There ain't no grave can hold my body down
When I hear that trumpet sound I'm gonna rise right out of the ground
Ain't no grave can hold my body down
</p>
</body>
<script type="text/javascript">
alert('Last Appearance');
setTimeout(function(){ alert('Last appearance 5000 ms') }, 5000);
</script>
</html>
解决方案
在您的示例中,脚本是内联的,因此没有真正下载任何内容。但是脚本是在 html 的其余部分完成加载后执行的。
这是一个可能更清楚的例子:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Loader Sequence</title>
<link rel="stylesheet" type="text/css" href="style/style1.css">
<script type="text/javascript">
alert('Head script\nThe body does not show yet');
</script>
</head>
<body>
<p>HTML parse and render</p>
<img style="max-width: 70%; height: auto; border: 1px solid red;" src="https://i.stack.imgur.com/wfL82.png">
<p>
There ain't no grave can hold my body down
There ain't no grave can hold my body down
When I hear that trumpet sound I'm gonna rise right out of the ground
Ain't no grave can hold my body down
</p>
</body>
<script type="text/javascript">
alert('Bottom script\nThe body has been rendered');
</script>
</html>
另一个例子,通过在加载之前和之后访问 DOM:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Loader Sequence</title>
<link rel="stylesheet" type="text/css" href="style/style1.css">
<script type="text/javascript">
// Here the paragraph has not been parsed yet and does not exist in the DOM
alert(document.getElementById('johnnycash') && document.getElementById('johnnycash').innerText);
</script>
</head>
<body>
<p>HTML parse and render</p>
<img style="max-width: 70%; height: auto; border: 1px solid red;" src="https://i.stack.imgur.com/wfL82.png">
<p id="johnnycash">
There ain't no grave can hold my body down
There ain't no grave can hold my body down
When I hear that trumpet sound I'm gonna rise right out of the ground
Ain't no grave can hold my body down
</p>
</body>
<script type="text/javascript">
// Here the paragraph has been parsed and exists in the DOM
alert(document.getElementById('johnnycash') && document.getElementById('johnnycash').innerText);
</script>
</html>
推荐阅读
- d3.js - 我可以从 Inkscape 导入 .svg,或者在 d3 中将 xml 代码用于复杂形状吗?
- sql - 我可以将同一查询中两个单独表的 SQL 查询的输出相乘吗?
- css - 将引导轮播指示器更改为项目符号
- python - 带有物理按钮的 PysimpleGUI 计数器
- c++ - 比较后选择最佳变量
- python - python使用lxml解析XML,给出正确的解析器参数
- excel - VBA提取字符串中的所有字段名
- java - 添加所有依赖项和插件时 pom.xml 出错
- node.js - 通过 Socket.io 上传录制的屏幕不起作用
- android - android janus webrtc ondatachannel未触发