gpt4 book ai didi

javascript、HTML、在 head 和 body 中编写 javascript 的区别

转载 作者:行者123 更新时间:2023-11-28 04:54:50 25 4
gpt4 key购买 nike

我正在学习 javascript,说实话,有些部分对我来说没有意义。像这个。我首先写了这段代码:

<body>
<script type="text/javascript">
function people(name, age){
this.name = name;
this.age = age;
this.ret = yearsLeft;
}

function yearsLeft(){
var numYears = 65 - this.age;
return numYears;
}

var sam = new people("sam forest", 39);
var billy = new people("billy wood", 45);

document.write(billy.ret());
</script>
</body>

我得到了结果。然而,我在第一个之后写了这个,并且得到了相同的结果:

<head>
<title>Javascript</title>

<script type="text/javascript">
function people(name, age){
this.name = name;
this.age = age;
this.ret = yearsLeft;
}

function yearsLeft(){
var numYears = 65 - this.age;
return numYears;
}

var sam = new people("sam forest", 39);
var billy = new people("billy wood", 45);
</script>
</head>
<body>
<script type="text/javascript">

document.write(billy.ret());
</script>
</body>

这是我的问题,当我以两种方式得到相同的结果时,有什么区别?

最佳答案

来自雅虎的Best Practices for Speeding Up Your Web Site :

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.

In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.

An alternative suggestion that often comes up is to use deferred scripts. The DEFER attribute indicates that the script does not contain document.write, and is a clue to browsers that they can continue rendering. Unfortunately, Firefox doesn't support the DEFER attribute. In Internet Explorer, the script may be deferred, but not as much as desired. If a script can be deferred, it can also be moved to the bottom of the page. That will make your web pages load faster.

因此,一般来说,最好将它们放在底部。然而,这并不总是可能的,而且通常也不会产生太大的影响。

关于javascript、HTML、在 head 和 body 中编写 javascript 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42621132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com