JavaScript脚本加载顺序

问题描述 投票:0回答:1

我获得了这张图片的参考script loading

但是在以下情况下,即使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 parsing
1个回答
0
投票

在您的示例中,脚本是内联的,因此没有真正下载任何内容。但是该脚本是在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之前和之后访问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>
© www.soinside.com 2019 - 2024. All rights reserved.