在HTML中,JavaScript可以写到程序的任何地方:<HTML>标签前, <BODY>标签前,<BODY>标签里面, <BODY>标签后, <HTML> 标签后.
下面,我们通过一个HTML中嵌套Javascript的小程序,来演示一下代码执行过程
1. 程序代码
2. 执行结果
<!DOCTYPE html>
<script>
alert("script-before Html");
document.write("<br>"+"script-before Html"+"<br>");
document.write("<h2 id ='pp1'> This is an example about HTML load process procedure </h2><h2 id = 'pp2'> This is an example about HTML load process procedure </h2><h2 id = 'pp3'> This is an example about HTML load process procedure </h2>");
</script>
<html lang="en">
<title> Test </title>
<head>
<script>
alert("script-head");
document.write("script-head"+"<br>");
</script>
</head>
<body onload="alert('html-tag');">
<script>
alert("script-body-begin");
document.write("script-body begin"+"<br>");
</script>
<h1> This is a HTML file Process Progress test file </h1>
<script>
alert("script-body-end");
document.write("script-body end"+"<br>");
</script>
</body>
<script>
alert("script-body-outer");
document.write("script-body-outer"+"<br>");
document.getElementById("pp2").innerHTML = "modified by script-body-outer";
</script>
</html>
<script>
alert("script-html-outer"+"<br>");
document.write("script-html-outer"+"<br>");
document.getElementById("pp3").innerHTML = "modified by script-htlm-outer";
</script>
2. 执行结果
下图是执行完<Body>的输出
下面是执行完最终的输出:
3 代码解释
1. 这个程序文件是顺序执行的,先执行<HTML>标签前==》<head>...</head> ==》<body>...</body> ==》<ody>后==><html>后
2. 在<HTML执行之前,调用JavaScript 创建了3个段落:
<h2 id ='pp1'> This is an example about HTML load process procedure </h2>
<h2 id = 'pp2'> This is an example about HTML load process procedure </h2>
<h2 id = 'pp3'> This is an example about HTML load process procedure </h2>");
3. 在<Body>和<html> 执行后,修改<h2>标签id为"pp2"和"pp3"的内容
</body>
<script>
alert("script-body-outer");
document.write("script-body-outer"+"<br>");
document.getElementById("pp2").innerHTML = "modified by script-body-outer";
</script>
</html>
<script>
alert("script-html-outer"+"<br>");
document.write("script-html-outer"+"<br>");
document.getElementById("pp3").innerHTML = "modified by script-htlm-outer";
</script>
4. 在<Html>标签后的Java语句,类似使用了Ajax机制,在文档加载完成,对部分内容进行了更改。