When embedding JavaScript in an HTML document, where is the proper place to put the <script>
tags and included JavaScript? I seem to recall that you are not supposed to place these in the <head>
section, but placing at the beginning of the <body>
section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the end of the <body>
section as a logical place for <script>
tags.
在HTML文档中嵌入JavaScript时,在哪里放置
So, where is the right place to put the <script>
tags?
那么,在哪里放置
(This question references this question, in which it was suggested that JavaScript function calls should be moved from <a>
tags to <script>
tags. I'm specifically using jQuery, but more general answers are also appropriate.)
(这个问题引用了这个问题,其中建议将JavaScript函数调用从标记移动到
20 个解决方案
#1
1447
Here's what happens when a browser loads a website with a <script>
tag on it:
当浏览器加载带有
- Fetch the HTML page (e.g. index.html)
- 获取HTML页面(例如index.html)
- Begin parsing the HTML
- 开始解析HTML
- The parser encounters a
<script>
tag referencing an external script file. - 解析器遇到引用外部脚本文件的
- The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
- 浏览器请求脚本文件。同时,解析器阻塞并停止解析页面上的其他HTML。
- After some time the script is downloaded and subsequently executed.
- 一段时间后,脚本被下载并随后执行。
- The parser continues parsing the rest of the HTML document.
- 解析器继续解析HTML文档的其余部分。
Step 4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.
第4步导致糟糕的用户体验。你的网站基本上停止加载,直到你下载了所有的脚本。如果有一件事是用户讨厌的,那就是等待网站加载。
Why does this even happen?
Any script can insert its own HTML via document.write()
or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded & executed before it can safely parse the rest of the document. After all, the script could have inserted its own HTML in the document.
任何脚本都可以通过document.write()或其他DOM操作插入自己的HTML。这意味着解析器必须等到脚本被下载和执行后才能安全地解析文档的其余部分。毕竟,脚本可以在文档中插入自己的HTML。
However, most javascript developers no longer manipulate the DOM while the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:
然而,大多数javascript开发人员不再在文档加载时操作DOM。相反,在修改文档之前,它们会等待文档被加载。例如:
<!-- index.html -->
<html>
<head>
<title>My Page</title>
<script type="text/javascript" src="my-script.js"></script>
</head>
<body>
<div id="user-greeting">Welcome back, user</div>
</body>
</html>
Javascript:
Javascript:
// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});
Because your browser does not know my-script.js isn't going to modify the document until it has been downloaded & executed, the parser stops parsing.
因为您的浏览器不知道my-script。js不会修改文档,直到它被下载并执行,解析器停止解析。
Antiquated recommendation
The old approach to solving this problem was to put <script>
tags at the bottom of your <body>
, because this ensures the parser isn't blocked until the very end.
解决这个问题的旧方法是将
This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts & stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.
这种方法有自己的问题:浏览器在解析整个文档之前不能开始下载脚本。对于具有大型脚本和样式表的大型网站,能够尽快下载脚本对性能非常重要。如果你的网站在2秒内没有加载,人们就会去另一个网站。
In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.
在一个最优的解决方案中,浏览器将开始尽可能快地下载脚本,同时解析文档的其余部分。
The modern approach
Today, browsers support the async
and defer
attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.
现在,浏览器支持异步和延迟脚本上的属性。这些属性告诉浏览器在下载脚本时继续解析是安全的。
async
<script type="text/javascript" src="path/to/script1.js" async></script>
<script type="text/javascript" src="path/to/script2.js" async></script>
Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible to script 2 is downloaded & executed before script 1.
带有async属性的脚本是异步执行的。这意味着脚本在下载后立即执行,同时不会阻塞浏览器。这意味着可以在脚本1之前下载并执行脚本2。
According to http://caniuse.com/#feat=script-async, 90% of all browsers support this.
根据http://caniuse.com/#feat=脚本-异步,90%的浏览器都支持这一点。
defer
<script type="text/javascript" src="path/to/script1.js" defer></script>
<script type="text/javascript" src="path/to/script2.js" defer></script>
Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.
具有延迟属性的脚本按顺序执行(例如,第一个脚本1,然后第二个脚本2)。这也不会阻塞浏览器。
Unlike async scripts, defer scripts are only executed after the entire document has been loaded.
与异步脚本不同,延迟脚本在加载整个文档之后才执行。
According to http://caniuse.com/#feat=script-defer, 90% of all browsers support this. 92% support it at least partially.
根据http://caniuse.com/#feat=script- deferred, 90%的浏览器都支持这一点。92%的人至少部分支持。
An important note on browser compatibility: in some circumstances IE <= 9 may execute deferred scripts out of order. If you need to support those browsers, please read this first!
关于浏览器兼容性的一个重要注意:在某些情况下,IE <= 9可能会执行延迟脚本。如果您需要支持这些浏览器,请先阅读!
Conclusion
The current state-of-the-art is to put scripts in the <head>
tag and use the async
or defer
attributes. This allows your scripts to be downloaded asap without blocking your browser.
目前最先进的技术是将脚本放在标记中,并使用异步或延迟属性。这使您的脚本可以尽快下载,而不会阻塞您的浏览器。
The good thing is that your website should still load correctly on the 20% of browsers that do not support these attributes while speeding up the other 80%.
好的一面是,你的网站仍然应该在20%不支持这些属性的浏览器上正确地加载,同时加速其他80%的浏览器。
#2
218
Just before the closing body tag, as stated on
就在结束体标签之前,如上面所述
http://developer.yahoo.com/performance/rules.html#js_bottom
http://developer.yahoo.com/performance/rules.html js_bottom
Put Scripts at the Bottom
把脚本放在底部
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规范建议浏览器以每个主机名并行方式下载不超过两个组件。如果您从多个主机名提供映像,您可以同时获得两个以上的下载。虽然脚本正在下载,但是浏览器不会启动任何其他下载,即使是在不同的主机名上。
#3
52
Non-blocking script tags can be placed just about anywhere:
非阻塞脚本标签可以放置在任何地方:
<script src="script.js" async></script>
<script src="script.js" defer></script>
<script src="script.js" async defer></script>
-
async
script will be executed asynchronously as soon as it is available - 当异步脚本可用时,它将被异步执行
-
defer
script is executed when the document has finished parsing - 延迟脚本在文档完成解析后执行
-
async defer
script falls back to the defer behavior if async is not supported - 如果不支持异步,那么异步延迟脚本将返回到延迟行为
Such scripts will be executed asynchronously/after document ready, which means you cannot do this:
这些脚本将在准备好文档后异步执行,这意味着您不能这样做:
<script src="jquery.js" async></script>
<script>jQuery(something);</script>
<!--
* might throw "jQuery is not defined" error
* defer will not work either
-->
Or this:
或:
<script src="document.write(something).js" async></script>
<!--
* might issue "cannot write into document from an asynchronous script" warning
* defer will not work either
-->
Or this:
或:
<script src="jquery.js" async></script>
<script src="jQuery(something).js" async></script>
<!--
* might throw "jQuery is not defined" error (no guarantee which script runs first)
* defer will work in sane browsers
-->
Or this:
或:
<script src="document.getElementById(header).js" async></script>
<div id="header"></div>
<!--
* might not locate #header (script could fire before parser looks at the next line)
* defer will work in sane browsers
-->
Having said that, asynchronous scripts offer these advantages:
尽管如此,异步脚本提供了以下优点:
-
Parallel download of resources:
Browser can download stylesheets, images and other scripts in parallel without waiting for a script to download and execute. - 并行下载资源:浏览器可以并行下载样式表、图像和其他脚本,而不需要等待脚本下载和执行。
-
Source order independence:
You can place the scripts inside head or body without worrying about blocking (useful if you are using a CMS). Execution order still matters though. - 源代码顺序独立:您可以将脚本放在头部或身体内部,而不必担心阻塞(如果您使用CMS,这将非常有用)。但是执行顺序仍然很重要。
It is possible to circumvent the execution order issues by using external scripts that support callbacks. Many third party JavaScript APIs now support non-blocking execution. Here is an example of loading the Google Maps API asynchronously.
通过使用支持回调的外部脚本,可以避免执行顺序问题。许多第三方JavaScript api现在支持非阻塞执行。下面是异步加载谷歌映射API的示例。
#4
36
The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script>
tags at the end of the document body so they don't block rendering of the page.
标准的建议,由雅虎推广!出色的性能团队将
But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:
但是有一些更新的方法可以提供更好的性能,如本文关于谷歌分析JavaScript文件加载时间的回答所述:
There are some great slides by Steve Souders (client-side performance expert) about:
Steve Souders(客户端性能专家)写了一些很棒的幻灯片:
- Different techniques to load external JavaScript files in parallel
- 可以并行加载外部JavaScript文件的不同技术。
- their effect on loading time and page rendering
- 它们对加载时间和页面呈现的影响
- what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).
- 浏览器显示的“进展”指标是什么?“载入”状态栏,沙漏鼠标光标。
#5
19
If you are using JQuery then put the javascript wherever you find it best and use $(document).ready()
to ensure that things are loaded properly before executing any functions.
如果您正在使用JQuery,那么请将javascript放在您认为最好的位置,并使用$(document).ready()确保在执行任何函数之前正确地加载所有内容。
On a side note: I like all my script tags in the <head>
section as that seems to be the cleanest place.
附带说明:我喜欢部分中的所有脚本标记,因为这似乎是最干净的地方。
#6
8
XHTML Won't Validate if the script is anywhere other than within the head element. turns out it can be everywhere.
XHTML不会验证脚本是否在head元素之外的其他地方。事实证明它无处不在。
You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).
您可以使用jQuery之类的东西来延迟执行,这样无论它放在哪里(除了解析期间性能受到的影响很小)。
#7
7
<script src="myjs.js"></script>
</body>
script tag should be use always before body close or Bottom in HTML file.
在HTML文件中,脚本标签应该总是在主体关闭或底部之前使用。
then you can see content of the page first before loading js file.
然后可以在加载js文件之前先看到页面内容。
check this if require : http://stevesouders.com/hpws/rule-js-bottom.php
如果需要,请检查这个:http://stevesouders.com/hpws/rules -js-bottom.php
#8
5
The conventional (and widely accepted) answer is "at the bottom", because then the entire DOM will have been loaded before anything can start executing.
传统的(并且被广泛接受的)答案是“在底层”,因为在任何事情开始执行之前,整个DOM都将被加载。
There are dissenters, for various reasons, starting with the available practice to intentionally begin execution with a page onload event.
由于各种原因,有一些持不同意见的人,他们从可用的实践开始,有意地以页面onload事件开始执行。
#9
0
Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.
根据脚本及其使用情况,最好的方法(就页面加载和呈现时间而言)可能是不使用常规的
There are some different techniques, but the most straight forward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.
有一些不同的技术,但是最直接的方法是在窗口时使用document.createElement(“script”)。onload事件触发。然后在页面本身呈现时首先加载脚本,这样就不会影响用户等待页面出现的时间。
This naturally requires that the script itself is not needed for the rendering of the page.
这自然要求不需要脚本本身来呈现页面。
For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow but now at Google).
有关更多信息,请参见Steve Souders (YSlow的创建者,现在在谷歌)的post耦合async脚本。
#10
0
Depends, if you are loading a script that's necessary to style your page / using actions in your page (like click of a button) then you better place it on the top. If your styling is 100% CSS and you have all fallback options for the button actions then you can place it in the bottom.
视情况而定,如果您正在加载一个脚本,该脚本需要对页面进行样式化/使用页面中的操作(如单击按钮),那么您最好将其放在顶部。如果你的样式是100% CSS并且你有所有的后退选项按钮动作,那么你可以把它放在底部。
Or best thing (if that's not a concern) is you can make a modal loading box, place your javascript at the bottom of your page and make it disappear when the last line of your script gets loaded. This way you can avoid users using actions in your page before the scripts are loaded. And also avoid the improper styling.
或者最好的事情(如果这不是一个问题的话)是你可以做一个模式加载框,把你的javascript放在页面的底部,当你的脚本的最后一行被加载时它就消失了。这样可以避免用户在加载脚本之前在页面中使用操作。还要避免不恰当的样式。
#11
0
Script blocks DOM load untill it's loaded and executed.
脚本阻止DOM加载,直到它被加载并执行。
If you place scripts at the end of <body>
all of DOM has chance to load and render (page will "display" faster). <script>
will have access to all of those DOM elements.
如果您将脚本放在的末尾,所有DOM都有加载和呈现的机会(页面将“显示”更快)。 <脚本> 将访问所有这些DOM元素。
In other hand placing it after <body>
start or above will execute script (where there's still no DOM elements).
另一方面,将它放在 start或以上之后将执行脚本(在那里仍然没有DOM元素)。
You are including jQuery which means you can place it wherever you wish and use .ready()
包括jQuery,这意味着可以将它放置在任何需要的地方,并使用.ready()
#12
0
-
If you still care a lot about support and performance in IE<10, it's best to ALWAYS make your script tags the last tags of your HTML body. That way, you're certain that the rest of the DOM has been loaded and you won't block and rendering.
如果您仍然非常关心IE<10中的支持和性能,那么最好始终将脚本标记作为HTML主体的最后标记。这样,您就可以确定DOM的其余部分已经被加载,并且不会阻塞和呈现。
-
If you don't care too much anymore about IE<10, you might want to put your scripts in the head of your document and use
defer
to ensure they only run after your DOM has been loaded (<script type="text/javascript" src="path/to/script1.js" defer></script>
). If you still want your code to work in IE<10, don't forget to wrap your code in awindow.onload
even, though!如果您不再太在意IE<10,那么您可能希望将脚本放在文档的头部,并使用deferred来确保它们只在DOM加载之后才运行(
#13
0
I think it depends on the webpage execution. If the page that you want to display can not displayed properly without loading JavaScript first then you should include JavaScript file first. But If you can display/render a webpage without initially download JavaScript file, then you should put JavaScript code at the bottom of the page. Because it will emulate a speedy page load, and from an user's point of view it would seems like that page is loading faster.
我认为这取决于网页的执行情况。如果您想要显示的页面在没有加载JavaScript之前不能正常显示,那么您应该首先包含JavaScript文件。但是,如果您可以显示/呈现一个网页,而不需要最初下载JavaScript文件,那么您应该将JavaScript代码放在页面的底部。因为它将模拟快速的页面加载,并且从用户的角度来看,这个页面的加载速度似乎更快。
#14
0
You can place most of <script>
references at the end of <body>
,
But If there are active components on your page which are using external scripts,
then their dependency (js files) should come before that (ideally in head tag).
您可以将大多数
#15
0
the best place to write your JavaScript
code in the end of document code after tag to load the document then execute js code. and if u write JQuery
code write
在文档代码的末尾编写JavaScript代码以加载文档,然后执行js代码的最佳位置。如果你写JQuery代码
$(document).ready (function{
//your code here
});
#16
0
Including scripts at the end is mainly used where the content/ styles of the website is to be shown first.
包括脚本在结尾,主要是使用的内容/风格的网站是首先显示。
including the scripts in the head loads the scripts early and can be used before the loading of the whole web site.
在head中包含脚本可以提前加载脚本,并且可以在加载整个web站点之前使用。
if the scripts are entered at last the validation will happen only after the loading of the entire styles and design which is not appreciated for fast responsive websites.
如果脚本最终被输入,验证将只会在加载整个样式和设计之后进行,而这在快速响应的网站上是不受欢迎的。
#17
0
At The End of HTML Document
在HTML文档的末尾
So that it will not effect the loading of the HTML document in the browser at the time of execution.
这样在执行时不会影响在浏览器中加载HTML文档。
#18
0
Scripts can be placed in the , or in the section of an HTML page, or in both.
脚本可以放在HTML页面的,或HTML页面的部分中,也可以放在两者中。
<head>
<script></script>
</head>
or here
<body>
<script></script>
</body>
but for best practise to ignore any error you must put between body tag because if any problem discover in javascript, html not be stop work but if you but between header tag if any problem discover that will stop your page work
但是为了更好地练习忽略任何错误,您必须在body标记之间放置,因为如果在javascript中发现任何问题,html不是停止工作,而是在header标记之间,如果发现任何问题,将停止页面工作
Blockquote
引用
#19
-2
It makes more sense to me to include the script after the HTML. Because most of the time I need the Dom to load before I execute my script. I could put it in the head tag but I don't like all the Document loading listener overhead. I want my code to be short and sweet and easy to read.
在HTML后面包含脚本对我来说更有意义。因为大多数时候,在执行脚本之前,我需要加载Dom。我可以把它放在head标签中但是我不喜欢所有的文档加载监听器。我希望我的代码短小、甜美、易于阅读。
I've heard old versions of safari was quarky when adding your script outside of the head tag but I say who cares. I don't know anybody using that old crap do you.
我听说旧版本的safari在添加head标签之外的脚本时是夸克级的,但我要说谁在乎呢。我不知道有谁用过那种老掉牙的废话,你知道吗?
Good question by the way.
好问题。
#20
-6
You can place where you want the scripts and one is not better than another practice.
您可以将脚本放置在您想要的位置,其中一个并不比另一个实践更好。
the situation is as follows:
情况如下:
The page load linearly, "top-down", so if you put the script in the head ensures that it starts to load before everything, now, if you put it inside the body mixed with the code can cause page loads a unsightly manner.
页面是线性加载的,“自顶向下”,所以如果你把脚本放在头部,确保它在所有东西之前开始加载,现在,如果你把它和代码混合在一起,会导致页面加载不雅观。
identify good practice does not depend on where.
识别好的实践并不取决于在哪里。
to support you, I will mention the following:
为了支持你,我将提及以下内容:
you can place:
您可以将:
and the page will load linearly
页面会线性加载
page is loaded asynchronously with other content
页面与其他内容异步加载
the content of the page will load before and after completion of loading the scripts are loaded
在加载脚本完成之前和之后,页面的内容将被加载
good practice here would be, when will implement each?
好的做法是,什么时候实施?
I hope I've been helpful, anything just answer me this issue.
我希望我能帮上忙,只要回答我这个问题。
#1
1447
Here's what happens when a browser loads a website with a <script>
tag on it:
当浏览器加载带有
- Fetch the HTML page (e.g. index.html)
- 获取HTML页面(例如index.html)
- Begin parsing the HTML
- 开始解析HTML
- The parser encounters a
<script>
tag referencing an external script file. - 解析器遇到引用外部脚本文件的
- The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
- 浏览器请求脚本文件。同时,解析器阻塞并停止解析页面上的其他HTML。
- After some time the script is downloaded and subsequently executed.
- 一段时间后,脚本被下载并随后执行。
- The parser continues parsing the rest of the HTML document.
- 解析器继续解析HTML文档的其余部分。
Step 4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.
第4步导致糟糕的用户体验。你的网站基本上停止加载,直到你下载了所有的脚本。如果有一件事是用户讨厌的,那就是等待网站加载。
Why does this even happen?
Any script can insert its own HTML via document.write()
or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded & executed before it can safely parse the rest of the document. After all, the script could have inserted its own HTML in the document.
任何脚本都可以通过document.write()或其他DOM操作插入自己的HTML。这意味着解析器必须等到脚本被下载和执行后才能安全地解析文档的其余部分。毕竟,脚本可以在文档中插入自己的HTML。
However, most javascript developers no longer manipulate the DOM while the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:
然而,大多数javascript开发人员不再在文档加载时操作DOM。相反,在修改文档之前,它们会等待文档被加载。例如:
<!-- index.html -->
<html>
<head>
<title>My Page</title>
<script type="text/javascript" src="my-script.js"></script>
</head>
<body>
<div id="user-greeting">Welcome back, user</div>
</body>
</html>
Javascript:
Javascript:
// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});
Because your browser does not know my-script.js isn't going to modify the document until it has been downloaded & executed, the parser stops parsing.
因为您的浏览器不知道my-script。js不会修改文档,直到它被下载并执行,解析器停止解析。
Antiquated recommendation
The old approach to solving this problem was to put <script>
tags at the bottom of your <body>
, because this ensures the parser isn't blocked until the very end.
解决这个问题的旧方法是将
This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts & stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.
这种方法有自己的问题:浏览器在解析整个文档之前不能开始下载脚本。对于具有大型脚本和样式表的大型网站,能够尽快下载脚本对性能非常重要。如果你的网站在2秒内没有加载,人们就会去另一个网站。
In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.
在一个最优的解决方案中,浏览器将开始尽可能快地下载脚本,同时解析文档的其余部分。
The modern approach
Today, browsers support the async
and defer
attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.
现在,浏览器支持异步和延迟脚本上的属性。这些属性告诉浏览器在下载脚本时继续解析是安全的。
async
<script type="text/javascript" src="path/to/script1.js" async></script>
<script type="text/javascript" src="path/to/script2.js" async></script>
Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible to script 2 is downloaded & executed before script 1.
带有async属性的脚本是异步执行的。这意味着脚本在下载后立即执行,同时不会阻塞浏览器。这意味着可以在脚本1之前下载并执行脚本2。
According to http://caniuse.com/#feat=script-async, 90% of all browsers support this.
根据http://caniuse.com/#feat=脚本-异步,90%的浏览器都支持这一点。
defer
<script type="text/javascript" src="path/to/script1.js" defer></script>
<script type="text/javascript" src="path/to/script2.js" defer></script>
Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.
具有延迟属性的脚本按顺序执行(例如,第一个脚本1,然后第二个脚本2)。这也不会阻塞浏览器。
Unlike async scripts, defer scripts are only executed after the entire document has been loaded.
与异步脚本不同,延迟脚本在加载整个文档之后才执行。
According to http://caniuse.com/#feat=script-defer, 90% of all browsers support this. 92% support it at least partially.
根据http://caniuse.com/#feat=script- deferred, 90%的浏览器都支持这一点。92%的人至少部分支持。
An important note on browser compatibility: in some circumstances IE <= 9 may execute deferred scripts out of order. If you need to support those browsers, please read this first!
关于浏览器兼容性的一个重要注意:在某些情况下,IE <= 9可能会执行延迟脚本。如果您需要支持这些浏览器,请先阅读!
Conclusion
The current state-of-the-art is to put scripts in the <head>
tag and use the async
or defer
attributes. This allows your scripts to be downloaded asap without blocking your browser.
目前最先进的技术是将脚本放在标记中,并使用异步或延迟属性。这使您的脚本可以尽快下载,而不会阻塞您的浏览器。
The good thing is that your website should still load correctly on the 20% of browsers that do not support these attributes while speeding up the other 80%.
好的一面是,你的网站仍然应该在20%不支持这些属性的浏览器上正确地加载,同时加速其他80%的浏览器。
#2
218
Just before the closing body tag, as stated on
就在结束体标签之前,如上面所述
http://developer.yahoo.com/performance/rules.html#js_bottom
http://developer.yahoo.com/performance/rules.html js_bottom
Put Scripts at the Bottom
把脚本放在底部
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规范建议浏览器以每个主机名并行方式下载不超过两个组件。如果您从多个主机名提供映像,您可以同时获得两个以上的下载。虽然脚本正在下载,但是浏览器不会启动任何其他下载,即使是在不同的主机名上。
#3
52
Non-blocking script tags can be placed just about anywhere:
非阻塞脚本标签可以放置在任何地方:
<script src="script.js" async></script>
<script src="script.js" defer></script>
<script src="script.js" async defer></script>
-
async
script will be executed asynchronously as soon as it is available - 当异步脚本可用时,它将被异步执行
-
defer
script is executed when the document has finished parsing - 延迟脚本在文档完成解析后执行
-
async defer
script falls back to the defer behavior if async is not supported - 如果不支持异步,那么异步延迟脚本将返回到延迟行为
Such scripts will be executed asynchronously/after document ready, which means you cannot do this:
这些脚本将在准备好文档后异步执行,这意味着您不能这样做:
<script src="jquery.js" async></script>
<script>jQuery(something);</script>
<!--
* might throw "jQuery is not defined" error
* defer will not work either
-->
Or this:
或:
<script src="document.write(something).js" async></script>
<!--
* might issue "cannot write into document from an asynchronous script" warning
* defer will not work either
-->
Or this:
或:
<script src="jquery.js" async></script>
<script src="jQuery(something).js" async></script>
<!--
* might throw "jQuery is not defined" error (no guarantee which script runs first)
* defer will work in sane browsers
-->
Or this:
或:
<script src="document.getElementById(header).js" async></script>
<div id="header"></div>
<!--
* might not locate #header (script could fire before parser looks at the next line)
* defer will work in sane browsers
-->
Having said that, asynchronous scripts offer these advantages:
尽管如此,异步脚本提供了以下优点:
-
Parallel download of resources:
Browser can download stylesheets, images and other scripts in parallel without waiting for a script to download and execute. - 并行下载资源:浏览器可以并行下载样式表、图像和其他脚本,而不需要等待脚本下载和执行。
-
Source order independence:
You can place the scripts inside head or body without worrying about blocking (useful if you are using a CMS). Execution order still matters though. - 源代码顺序独立:您可以将脚本放在头部或身体内部,而不必担心阻塞(如果您使用CMS,这将非常有用)。但是执行顺序仍然很重要。
It is possible to circumvent the execution order issues by using external scripts that support callbacks. Many third party JavaScript APIs now support non-blocking execution. Here is an example of loading the Google Maps API asynchronously.
通过使用支持回调的外部脚本,可以避免执行顺序问题。许多第三方JavaScript api现在支持非阻塞执行。下面是异步加载谷歌映射API的示例。
#4
36
The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script>
tags at the end of the document body so they don't block rendering of the page.
标准的建议,由雅虎推广!出色的性能团队将
But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:
但是有一些更新的方法可以提供更好的性能,如本文关于谷歌分析JavaScript文件加载时间的回答所述:
There are some great slides by Steve Souders (client-side performance expert) about:
Steve Souders(客户端性能专家)写了一些很棒的幻灯片:
- Different techniques to load external JavaScript files in parallel
- 可以并行加载外部JavaScript文件的不同技术。
- their effect on loading time and page rendering
- 它们对加载时间和页面呈现的影响
- what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).
- 浏览器显示的“进展”指标是什么?“载入”状态栏,沙漏鼠标光标。
#5
19
If you are using JQuery then put the javascript wherever you find it best and use $(document).ready()
to ensure that things are loaded properly before executing any functions.
如果您正在使用JQuery,那么请将javascript放在您认为最好的位置,并使用$(document).ready()确保在执行任何函数之前正确地加载所有内容。
On a side note: I like all my script tags in the <head>
section as that seems to be the cleanest place.
附带说明:我喜欢部分中的所有脚本标记,因为这似乎是最干净的地方。
#6
8
XHTML Won't Validate if the script is anywhere other than within the head element. turns out it can be everywhere.
XHTML不会验证脚本是否在head元素之外的其他地方。事实证明它无处不在。
You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).
您可以使用jQuery之类的东西来延迟执行,这样无论它放在哪里(除了解析期间性能受到的影响很小)。
#7
7
<script src="myjs.js"></script>
</body>
script tag should be use always before body close or Bottom in HTML file.
在HTML文件中,脚本标签应该总是在主体关闭或底部之前使用。
then you can see content of the page first before loading js file.
然后可以在加载js文件之前先看到页面内容。
check this if require : http://stevesouders.com/hpws/rule-js-bottom.php
如果需要,请检查这个:http://stevesouders.com/hpws/rules -js-bottom.php
#8
5
The conventional (and widely accepted) answer is "at the bottom", because then the entire DOM will have been loaded before anything can start executing.
传统的(并且被广泛接受的)答案是“在底层”,因为在任何事情开始执行之前,整个DOM都将被加载。
There are dissenters, for various reasons, starting with the available practice to intentionally begin execution with a page onload event.
由于各种原因,有一些持不同意见的人,他们从可用的实践开始,有意地以页面onload事件开始执行。
#9
0
Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.
根据脚本及其使用情况,最好的方法(就页面加载和呈现时间而言)可能是不使用常规的
There are some different techniques, but the most straight forward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.
有一些不同的技术,但是最直接的方法是在窗口时使用document.createElement(“script”)。onload事件触发。然后在页面本身呈现时首先加载脚本,这样就不会影响用户等待页面出现的时间。
This naturally requires that the script itself is not needed for the rendering of the page.
这自然要求不需要脚本本身来呈现页面。
For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow but now at Google).
有关更多信息,请参见Steve Souders (YSlow的创建者,现在在谷歌)的post耦合async脚本。
#10
0
Depends, if you are loading a script that's necessary to style your page / using actions in your page (like click of a button) then you better place it on the top. If your styling is 100% CSS and you have all fallback options for the button actions then you can place it in the bottom.
视情况而定,如果您正在加载一个脚本,该脚本需要对页面进行样式化/使用页面中的操作(如单击按钮),那么您最好将其放在顶部。如果你的样式是100% CSS并且你有所有的后退选项按钮动作,那么你可以把它放在底部。
Or best thing (if that's not a concern) is you can make a modal loading box, place your javascript at the bottom of your page and make it disappear when the last line of your script gets loaded. This way you can avoid users using actions in your page before the scripts are loaded. And also avoid the improper styling.
或者最好的事情(如果这不是一个问题的话)是你可以做一个模式加载框,把你的javascript放在页面的底部,当你的脚本的最后一行被加载时它就消失了。这样可以避免用户在加载脚本之前在页面中使用操作。还要避免不恰当的样式。
#11
0
Script blocks DOM load untill it's loaded and executed.
脚本阻止DOM加载,直到它被加载并执行。
If you place scripts at the end of <body>
all of DOM has chance to load and render (page will "display" faster). <script>
will have access to all of those DOM elements.
如果您将脚本放在的末尾,所有DOM都有加载和呈现的机会(页面将“显示”更快)。 <脚本> 将访问所有这些DOM元素。
In other hand placing it after <body>
start or above will execute script (where there's still no DOM elements).
另一方面,将它放在 start或以上之后将执行脚本(在那里仍然没有DOM元素)。
You are including jQuery which means you can place it wherever you wish and use .ready()
包括jQuery,这意味着可以将它放置在任何需要的地方,并使用.ready()
#12
0
-
If you still care a lot about support and performance in IE<10, it's best to ALWAYS make your script tags the last tags of your HTML body. That way, you're certain that the rest of the DOM has been loaded and you won't block and rendering.
如果您仍然非常关心IE<10中的支持和性能,那么最好始终将脚本标记作为HTML主体的最后标记。这样,您就可以确定DOM的其余部分已经被加载,并且不会阻塞和呈现。
-
If you don't care too much anymore about IE<10, you might want to put your scripts in the head of your document and use
defer
to ensure they only run after your DOM has been loaded (<script type="text/javascript" src="path/to/script1.js" defer></script>
). If you still want your code to work in IE<10, don't forget to wrap your code in awindow.onload
even, though!如果您不再太在意IE<10,那么您可能希望将脚本放在文档的头部,并使用deferred来确保它们只在DOM加载之后才运行(
#13
0
I think it depends on the webpage execution. If the page that you want to display can not displayed properly without loading JavaScript first then you should include JavaScript file first. But If you can display/render a webpage without initially download JavaScript file, then you should put JavaScript code at the bottom of the page. Because it will emulate a speedy page load, and from an user's point of view it would seems like that page is loading faster.
我认为这取决于网页的执行情况。如果您想要显示的页面在没有加载JavaScript之前不能正常显示,那么您应该首先包含JavaScript文件。但是,如果您可以显示/呈现一个网页,而不需要最初下载JavaScript文件,那么您应该将JavaScript代码放在页面的底部。因为它将模拟快速的页面加载,并且从用户的角度来看,这个页面的加载速度似乎更快。
#14
0
You can place most of <script>
references at the end of <body>
,
But If there are active components on your page which are using external scripts,
then their dependency (js files) should come before that (ideally in head tag).
您可以将大多数
#15
0
the best place to write your JavaScript
code in the end of document code after tag to load the document then execute js code. and if u write JQuery
code write
在文档代码的末尾编写JavaScript代码以加载文档,然后执行js代码的最佳位置。如果你写JQuery代码
$(document).ready (function{
//your code here
});
#16
0
Including scripts at the end is mainly used where the content/ styles of the website is to be shown first.
包括脚本在结尾,主要是使用的内容/风格的网站是首先显示。
including the scripts in the head loads the scripts early and can be used before the loading of the whole web site.
在head中包含脚本可以提前加载脚本,并且可以在加载整个web站点之前使用。
if the scripts are entered at last the validation will happen only after the loading of the entire styles and design which is not appreciated for fast responsive websites.
如果脚本最终被输入,验证将只会在加载整个样式和设计之后进行,而这在快速响应的网站上是不受欢迎的。
#17
0
At The End of HTML Document
在HTML文档的末尾
So that it will not effect the loading of the HTML document in the browser at the time of execution.
这样在执行时不会影响在浏览器中加载HTML文档。
#18
0
Scripts can be placed in the , or in the section of an HTML page, or in both.
脚本可以放在HTML页面的,或HTML页面的部分中,也可以放在两者中。
<head>
<script></script>
</head>
or here
<body>
<script></script>
</body>
but for best practise to ignore any error you must put between body tag because if any problem discover in javascript, html not be stop work but if you but between header tag if any problem discover that will stop your page work
但是为了更好地练习忽略任何错误,您必须在body标记之间放置,因为如果在javascript中发现任何问题,html不是停止工作,而是在header标记之间,如果发现任何问题,将停止页面工作
Blockquote
引用
#19
-2
It makes more sense to me to include the script after the HTML. Because most of the time I need the Dom to load before I execute my script. I could put it in the head tag but I don't like all the Document loading listener overhead. I want my code to be short and sweet and easy to read.
在HTML后面包含脚本对我来说更有意义。因为大多数时候,在执行脚本之前,我需要加载Dom。我可以把它放在head标签中但是我不喜欢所有的文档加载监听器。我希望我的代码短小、甜美、易于阅读。
I've heard old versions of safari was quarky when adding your script outside of the head tag but I say who cares. I don't know anybody using that old crap do you.
我听说旧版本的safari在添加head标签之外的脚本时是夸克级的,但我要说谁在乎呢。我不知道有谁用过那种老掉牙的废话,你知道吗?
Good question by the way.
好问题。
#20
-6
You can place where you want the scripts and one is not better than another practice.
您可以将脚本放置在您想要的位置,其中一个并不比另一个实践更好。
the situation is as follows:
情况如下:
The page load linearly, "top-down", so if you put the script in the head ensures that it starts to load before everything, now, if you put it inside the body mixed with the code can cause page loads a unsightly manner.
页面是线性加载的,“自顶向下”,所以如果你把脚本放在头部,确保它在所有东西之前开始加载,现在,如果你把它和代码混合在一起,会导致页面加载不雅观。
identify good practice does not depend on where.
识别好的实践并不取决于在哪里。
to support you, I will mention the following:
为了支持你,我将提及以下内容:
you can place:
您可以将:
and the page will load linearly
页面会线性加载
page is loaded asynchronously with other content
页面与其他内容异步加载
the content of the page will load before and after completion of loading the scripts are loaded
在加载脚本完成之前和之后,页面的内容将被加载
good practice here would be, when will implement each?
好的做法是,什么时候实施?
I hope I've been helpful, anything just answer me this issue.
我希望我能帮上忙,只要回答我这个问题。