什么是优点和缺点:将javascript放在头部并放在身体关闭之前 [英] What's Pros and Cons: putting javascript in head and putting just before the body close

查看:139
本文介绍了什么是优点和缺点:将javascript放在头部并放在身体关闭之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数javascript和网页开发书/文章都说你必须把CSS放在head标签和页面底部的javascript中。

Most of javascript and web development books/articles says that you must put CSS in the head tag and javascript at the bottom of the page.

但是当我打开着名网站的html源代码,比如这个stackoverflow,我发现他们在头标签中放了一些js文件。

But when I open html source of famous websites such as this one stackoverflow, I find they put some js files in the head tag.

这两种方法的优点和缺点是什么,何时使用哪个?

What's Pros and Cons of both approaches and when to use which?

发现同一问题的另一个问题:
我应该在哪里声明我的页面中使用的JavaScript文件?在< head>< / head>或者靠近< / body>?

推荐答案

来自雅虎的加速网站的最佳实践


脚本引起的问题是
它们会阻止并行下载。
HTTP / 1.1规范表明
浏览器每个主机名并行下载不超过两个
组件。
如果您从多个
主机名提供图像,则可以并行获得超过两个
的下载量。虽然
a脚本正在下载,但是,
浏览器不会启动任何其他
下载,即使在不同的
主机名上也是如此。

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.

在某些情况下,
将脚本移到底部并不容易。如果,对于
示例,脚本使用
document.write插入
页面内容的一部分,则无法在页面中将
移动到较低位置。可能还有
范围界定问题。在许多情况下,
是解决这些
情况的方法。

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.

另一个建议,通常
出现是使用延期脚本。
DEFER属性表明
脚本不包含
document.write,并且是
浏览器的线索,他们可以继续
渲染。不幸的是,Firefox
不支持DEFER属性。
在Internet Explorer中,脚本可以延迟
,但不能超过
。如果脚本可以延期,
它也可以移动到页面
的底部。这将使您的网页
页面加载速度更快。

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.

因此,一般情况下,最好将它们放在最底层。但是,它并不总是可行的,而且通常不会使 产生很大的差异。

Therefore, in general, it is preferrable to put them at the bottom. However, it isn't always possible, and it often doesn't make that much of a difference anyway.

这篇关于什么是优点和缺点:将javascript放在头部并放在身体关闭之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆