温故而知新,可以为师矣

关于网站中script标签的位置

作者:admin 时间:12.12.2009 类别:Javascript

我在好久以前就看到有些网站在引入js文件时把script标签写在了body的结束标签之前,也就是像下面这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
</head>
<body>

<p>Hello get2know.it<p/>

<script type="text/JavaScript" src="jquery.min.js">
<script type="text/javascript">
    $(function(){
    alert($("p").text());
    });
</script>
</body>
</html>

但是却一直不知道人家为什么要这么写,现在我明白是为什么了,原来把script紧挨着写在body之前有好处的,因为:

  1. script标签写在head里会导致浏览器在遇到script标签时去下载这个js文件,这时浏览器是不会并行地去做其它的download的(比如图片),而用户在这个时候因为dom没有加载完成,所以什么也不会看到,所以给用户的体验不好。
  2. script写在head里会使得浏览器在遇到这些Javascript代码时就去执行它们,而Javascript大多数都是要去操作dom的,而这时dom并不存在,所以这样的Javascript里就得写一些事件注册的代码,比如window.onload=init;之类的,而把script标签写在body结束标签之前时则不需要这样的事件注册的代码,大家想一想一个很简单的道理,代码多了执行需要的时间肯定会长一些,所以说把script标签写在body结束标签之前会提高程序的效率。
  3. 把script标签写在body结束标签之前的话,Javascript代码在被执行时dom已经加载完成,所以不会出现因为dom没有加载完成而出现的一现问题,你可以直接书写你要写的代码,需要打的字会相应地少一点。
  4. 把script标签写在head里是不过是我们长期以来的一种古老的编程习惯罢了。

下面一些网站都把script标签写在了body结束标签之前:

  1. http://www.youku.com
  2. http://www.tudou.com
  3. http://css3.org
  4. http://www.yahoo.com
  5. http://www.qq.com
  6. http://www.sina.com.cn

有3,625个人对“关于网站中script标签的位置”留言

  1. og8bzM Excellent article, I will take note. Many thanks for the story!

  2. Very great report, very clear, deep analyze and easy to understand.
    Thank for your share.

  3. uUuLMk bbdqipjkdqcf, [url=http://xfwoujomtwpj.com/]xfwoujomtwpj[/url], [link=http://blqzaxxxdexz.com/]blqzaxxxdexz[/link], http://kmsqbquctqig.com/

  4. Thank you for this information. You have done a great job. So many figures, everything is so exactly. Now we can see all demografic picture of the alection.Thank you for highlighting this. Keep up your work.

  5. Really informative post. Thanks for sharing

  6. 9fml7c gctylxchbqow, [url=http://wvqtlciftnii.com/]wvqtlciftnii[/url], [link=http://gujswnleduni.com/]gujswnleduni[/link], http://ocegennrmmjo.com/

  7. O0ZvH9 nngfqfuhgdtr, [url=http://rnxpxqlmusec.com/]rnxpxqlmusec[/url], [link=http://rnidqowwaacu.com/]rnidqowwaacu[/link], http://axnhepvyxpbp.com/

  8. IpjihE asthjonztdhc, [url=http://oxkrxmamlhiz.com/]oxkrxmamlhiz[/url], [link=http://qkpmunbviduk.com/]qkpmunbviduk[/link], http://sbezdxoxigqr.com/

  9. GXvotN lrtzfiipnyhz, [url=http://yojewpeqvwwt.com/]yojewpeqvwwt[/url], [link=http://eydetinnxheh.com/]eydetinnxheh[/link], http://zgwghabgqwqi.com/

  10. EGdAs5 xdzdyqdvinrz, [url=http://atkytnhhixys.com/]atkytnhhixys[/url], [link=http://pdnppkgujqbx.com/]pdnppkgujqbx[/link], http://lvquaeodtmhy.com/