[Web]页面的执行顺序

今天在StackOverflow 上看了 一篇讨论页面加载顺序的文章

http://stackoverflow.com/questions/1795438/load-and-execution-sequence-of-a-web-page

1. html 页面元素下载到本地(还没有解析)

2. 浏览器的html 解析器开始解析页面,如果是外置资源则顺序加载并解析(参考下面的例子)

鉴于解析器是完全顺序并单线程执行的,所以页面里内置的 javascript 代码最好写在html 元素的后面而不是头部。

原文里有个例子可作为常考。

<html>

<head>

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

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

</script>

<link rel="stylesheets" type="text/css" href="abc.css"></link>

<style>h2{font-wight:bold;}</style>

<script>

$(document).ready(function(){

$("#img").attr("src", "kkk.png");

});

</script>

</head>

<body>

<img id="img" src="abc.jpg" style="width:400px;height:300px;"/>

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

</body>

</html>

roughly the execution flow is about as follows:

  1. The HTML document gets downloaded
  2. The parsing of the HTML document starts
  3. HTML Parsing reaches <script src="jquery.js" ...
  4. jquery.js is downloaded and parsed
  5. HTML parsing reaches <script src="abc.js" ...
  6. abc.js is downloaded, parsed and run
  7. HTML parsing reaches <link href="abc.css" ...
  8. abc.css is downloaded and parsed
  9. HTML parsing reaches <style>...</style>
  10. Internal CSS rules are parsed and defined
  11. HTML parsing reaches <script>...</script>
  12. Internal Javascript is parsed and run
  13. HTML Parsing reaches <img src="abc.jpg" ...
  14. abc.jpg is downloaded and displayed
  15. HTML Parsing reaches <script src="kkk.js" ...
  16. kkk.js is downloaded, parsed and run
  17. Parsing of HTML document ends
blog comments powered by Disqus