几年前,我受雇为符合 W3C/AA 标准的客户端应用程序开发 Web 前端。有人告诉我 CSS、JS 和其他非视觉/非演示性内容应该始终保留在 head 标签中。
示例
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="site.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="site.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Code here...
});
</script>
<head>
<body>
<div class="container">
...
</div>
</body>
</html>
这种方法一直对我有用,但在我目前的 Angular 色中,出于性能/执行原因,我被要求将 CSS 和 JS 引用全部移至文档底部
示例
<!DOCTYPE html>
<html>
<head>
...
<head>
<body>
<div class="container">
...
</div>
<link type="text/css" rel="stylesheet" href="site.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="site.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Code here...
});
</script>
</body>
</html>
有人告诉我,这样做不会违反任何合规性或可接受性标准,并且在某些情况下允许网站加载速度更快,但是这导致的问题比解决的问题还要多。
因此,我想知道是否应该坚持我的决定,将这些资源保留在 head 标签中,或者,另一方面,是否有任何令人信服的论点支持将资源标签放在底部或分散在文档中?
最佳答案
link
elements不能出现在body
中元素( unless they are used for Microdata or RDFa )。所以你的<link type="text/css" rel="stylesheet" href="site.css" />
必须是 head
的子项元素。
script
elements可以出现在 body
。放置 script
是否有意义取决于脚本和您的文档。元素作为 body
的最后一个子元素。例如,请参阅问题
- JavaScript on the bottom of the page? ,并且
- "JavaScript placed at the end of the document so the pages load faster" TRUE? (这是重复的,但包含其他答案)。
如果script
元素有 src
属性(即脚本是从外部文件导入的),您可以使用 async
和defer
控制其执行的属性:
async
:the script will be executed asynchronously, as soon as it is available
defer
:the script is executed when the page has finished parsing
默认(即既不是
async
也不是defer
):the script is fetched and executed immediately, before the user agent continues parsing the page
async
+defer
:cause legacy Web browsers that only support
defer
(and notasync
) to fall back to thedefer
behavior instead of the synchronous blocking behavior that is the default
关于javascript - W3C 和/或加载非可视网页资源的公认标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26863320/