首页 > 解决方案 > 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>

标签: htmlparsing

解决方案


在您的示例中,脚本是内联的,因此没有真正下载任何内容。但是脚本是在 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>


推荐阅读