JavaScript - 头部、身体还是 jQuery?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10994335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:56:23  来源:igfitidea点击:

JavaScript - head, body or jQuery?

javascriptjqueryhtml

提问by Bluefire

This question is just to clear some things up. Some things like this have been asked before, and this rounds them all up into one question - where should JavaScript go in the HTML document, or, more importantly, does it matter? So, one of the things I'm asking is, does

这个问题只是为了澄清一些事情。以前有人问过这样的问题,这将它们全部归结为一个问题 - JavaScript 应该放在 HTML 文档中的哪个位置,或者更重要的是,它是否重要?所以,我要问的一件事是,

<head>
<script type="text/javascript">
alert("Hello world!");
</script>
</head>

at all differ (in terms of functionality) from

完全不同(在功能方面)与

<body>
<!-- Code goes here -->
<script type="text/javascript">
alert("Hello world!");
</script>
</body>

More importantly, I want to focus on JS that modifies or uses elements from the DOM in any way. So I know that if you put something like document.getElementById("test").innerHTML = "Hello world!"before <element id="test"></element>in your body, then it won't work since the body is loaded from top to bottom, making the JS load first, which will then proceed to try to manipulate an element that doesn't exist yet. So it should, just like the above, either go in the <head>or just before the </body>tag. The question is, aside from organisation and sorting, does it matter which one of these is chosen, and if so, in what way?

更重要的是,我想专注于以任何方式修改或使用 DOM 元素的 JS。所以我知道如果你在你的身体里放了一些像document.getElementById("test").innerHTML = "Hello world!"以前一样的东西<element id="test"></element>,那么它就不会工作,因为身体是从上到下加载的,首先加载 JS,然后将继续尝试操作一个没有的元素还存在。所以它应该,就像上面一样,要么进入标签,要么<head>就在</body>标签之前。问题是,除了组织和排序之外,选择其中哪一个是否重要,如果是,以什么方式选择?

Of course, there is also a third method - the jQuery way:

当然,还有第三种方法——jQuery方式:

$(document).ready(function(){ /*Code goes here*/ });

That way, it doesn't matter where in the body you place the code, since it will only be executed when everything has loaded. The question here is, is it worth importing a huge JS library justto use a method the need for which could be replaced with an accurate placing of your scripts? I'd just like to clear things up a little here, if you would like to answer, go ahead! Summary: where should different kinds of scripts go - head or body, and/or does it matter? Is jQuery worth it just for the ready event?

这样,您将代码放置在正文中的哪个位置都没有关系,因为它只会在所有内容都加载后才会执行。这里的问题是,是否值得导入一个巨大的 JS 库只是为了使用一种可以用准确放置脚本替换的方法?我想在这里澄清一下,如果您想回答,请继续!总结:不同类型的脚本应该去哪里 - 头部或主体,和/或重要吗?jQuery 仅仅为了就绪事件值得吗?

采纳答案by Sarfraz

Most recommended method is to put it before </body>tag. Yahoo performance articlealso suggests that other than YSlowand Page Speedaddons by Yahoo and Google respectively.

最推荐的方法是把它放在</body>标签之前。雅虎性能文章还表明,除了雅虎和谷歌分别提供的YSlowPage Speed插件之外。

Quoting from Yahoo article linked above:

引用上面链接的雅虎文章:

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.

脚本引起的问题是它们会阻止并行下载。HTTP/1.1 规范建议浏览器每个主机名并行下载的组件不超过两个。如果您从多个主机名提供图像,则可以同时进行两次以上的下载。然而,在下载脚本时,浏览器不会启动任何其他下载,即使是在不同的主机名上。

When you put scripts in <head>tag, the browsers goes for them thereby keeping other stuff on hold until scripts are loaded which users will perceive like slow loading of the page. This is why you should put scripts at the bottom.

当您将脚本放入<head>标记中时,浏览器会选择它们,从而在脚本加载之前保持其他内容,用户会认为页面加载缓慢。这就是为什么你应该把脚本放在底部。

As for:

至于:

$(document).ready(function(){/*Code goes here*/});

It is fired when DOM is available and ready to be manipulated. If you put your code at the end, you won't necessarily need this but usually this is needed because you want to do something as soon asDOM is available for use.

当 DOM 可用并准备好被操纵时,它会被触发。如果你把你的代码放在最后,你不一定需要这个,但通常这是需要的,因为你想在DOM 可用时立即做一些事情。

回答by T.J. Crowder

Although common practice, putting scripttags in the headis not usually a good idea, as it holds up the rendering of your page until those scripts have been downloaded and processed (barring your use of asyncor deferand the browser supporting them).

尽管通常的做法是,在 中放置script标签head通常不是一个好主意,因为它会阻止页面的呈现,直到这些脚本被下载和处理(除非您使用asyncordefer和支持它们的浏览器)。

The usual recommendation is to put scripttags at the very end of the bodytag, e.g., just before </body>. That way, all of the DOM elements above the script will be accessible (see links below). One caveat on that is that there can be a brief moment when your page has been at least partially-rendered but your scripts not processed (yet), and if the user starts interacting with the page, they may do something to raise an event that your script hasn't had time to hook yet. So you need to be aware of that. This is one reason for progressive enhancement, which is the idea that the page will work without JavaScript, but work better with it. If you're doing a page/app that just won't work without JavaScript at all, you might include some inlinescript at the top of the bodytag (e.g., <script>minimal code here</script>) that hooks any bubbling events on document.bodyand either queues them for action when your script is loaded, or just asks the user to wait.

通常的建议是将script标签放在标签的最后body,例如,就在 之前</body>。这样,脚本上方的所有 DOM 元素都可以访问(请参阅下面的链接)。一个警告是,当您的页面至少部分呈现但您的脚本尚未处理(尚未)时,可能会有短暂的时刻,如果用户开始与页面交互,他们可能会做一些事情来引发一个事件你的脚本还没有来得及钩住。所以你需要意识到这一点。这是渐进增强的原因之一,即页面无需 JavaScript 也能工作,但使用它会更好。如果您正在制作一个完全没有 JavaScript 就无法运行的页面/应用程序,您可能会包含一些内联body标记顶部的脚本(例如,<script>minimal code here</script>)挂接任何冒泡事件,document.body并在您的脚本加载时将它们排队等待操作,或者只是要求用户等待。

Using features like jQuery's readyis fine, but not really necessary outside of libraries (e.g., if you're in control of where the scripttags will be, you don't usually need to use it; but if you're writing a jQuery plug-in that needs to do something on load [which is relatively rare, normally they just wait to be called], you usually do).

使用 jQuery 之类的ready功能很好,但在库之外并不是真正必要的(例如,如果您可以控制script标签的位置,则通常不需要使用它;但如果您正在编写 jQuery 插件)因为需要在加载时做一些事情[这是相对罕见的,通常他们只是等待被调用],你通常会这样做)。

More reading:

更多阅读:

回答by Luka

It is possible to download javascripts in parallel by doing something like this:

可以通过执行以下操作并行下载 javascripts:

(function () {
    var ele = document.createElement('script');
    ele.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
    ele.id = "JQuery";
    ele.onload = function () {
        //code to be executed when the document has been loaded
    };
    document.getElementsByTagName('head')[0].appendChild(ele);
})();

In the example it downloads minified JQuery v1.7.2 from Google, this is a good way to download JQuery since downloading it from Google is like using a CDN and if the user has been on a page that used the same file it might be cached and therefor doesn't need to be downloaded

在示例中,它从 Google 下载了缩小版的 JQuery v1.7.2,这是下载 JQuery 的好方法,因为从 Google 下载它就像使用 CDN,如果用户一直在使用相同文件的页面上,它可能会被缓存和因此不需要下载

There is a really good Google tech talk about this here http://www.youtube.com/watch?v=52gL93S3usU&feature=plcp

这里有一个非常好的谷歌技术讨论http://www.youtube.com/watch?v=52gL93S3usU&feature=plcp