加载外部 CSS 和 JavaScript 文件的顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4198624/
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
Order of loading external CSS and JavaScript files
提问by janfrode
I have a third party application that loads manycss and javascript files, and I now want to optimize this by concatinating all the javascripts into one file, compressed by the yuicompressor, but ... when we have a mix like:
我有一个加载许多css 和 javascript 文件的第三方应用程序,我现在想通过将所有 javascripts 合并到一个文件中来优化它,由 yuicompressor 压缩,但是......当我们有一个混合时:
<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
<link rel="stylesheet" href="style1.css" type="text/css" />
<script type="text/javascript" src="script3.js"></script>
<script type="text/javascript" src="script4.js"></script>
Does it matter that there's a css in the middle here? Should I concatinate and yuicompress the 4 javascripts and load them before the CSS or after?
这里中间有一个css有关系吗?我应该连接和 yuicompress 4 个 javascripts 并在 CSS 之前或之后加载它们吗?
回答by Sebastian Patane Masuelli
Check out Yahoo's Best Practices for Speeding Up Your Web Site, they recommend loading your css first (preferably in the header), and your js last (after all the content in the body). Google's best practicesalso recommended loading CSS first.
查看Yahoo's Best Practices for Speeding Your Web Site,他们建议先加载 css(最好在标题中),最后加载 js(在正文中的所有内容之后)。Google 的最佳实践还建议首先加载 CSS。
回答by Stefan Kendall
It depends. If all the JS only works on DOM ready, the order is unimportant. However, if there is any in-line javascript that changes CSS styling of DOM elements, then you'll have issues.
这取决于。如果所有的 JS 都只在 DOM 就绪的情况下工作,那么顺序就不重要了。但是,如果有任何内嵌 javascript 更改了 DOM 元素的 CSS 样式,那么您就会遇到问题。
More practically, you should probably put the CSS first so there is less time where the user needs to experience unstyled content.
更实际地,您可能应该将 CSS 放在首位,这样用户需要体验无样式内容的时间就会减少。
回答by palswim
It doesn't matter, although if loading takes a while, the user might see his page change appearance and wonder why. I'd put the CSS files first to have the style definitions in place before any DOM manipulation, most likely minimizing the visible change as the page loads, but it doesn't really matter in the end.
没关系,虽然如果加载需要一段时间,用户可能会看到他的页面改变外观并想知道为什么。在进行任何 DOM 操作之前,我会首先将 CSS 文件放在适当的位置,以便在页面加载时最小化可见的更改,但最终这并不重要。

