在网上的无数地方,我都看到过在JavaScript之前包含CSS的建议.推论一般是,of this form:
在订购CSS和JavaScript时,您需要您的CSS 先来一步.原因是呈现线程具有所有 它呈现页面所需的样式信息.如果JavaScript 包括,则JavaScript引擎必须在此之前将其全部解析 继续阅读下一组资源.这意味着渲染 线程不能完全显示页面,因为它没有所有 它需要的款式.
我的实际测试揭示了一些完全不同的东西:
我的测试装置
我使用以下Ruby脚本为各种资源生成特定的延迟:
require 'rubygems'
require 'eventmachine'
require 'evma_httpserver'
require 'date'
class Handler < EventMachine::Connection
include EventMachine::HttpServer
def process_http_request
resp = EventMachine::DelegatedHttpResponse.new( self )
return unless @http_query_string
path = @http_path_info
array = @http_query_string.split("&").map{|s| s.split("=")}.flatten
parsed = Hash[*array]
delay = parsed["delay"].to_i / 1000.0
jsdelay = parsed["jsdelay"].to_i
delay = 5 if (delay > 5)
jsdelay = 5000 if (jsdelay > 5000)
delay = 0 if (delay < 0)
jsdelay = 0 if (jsdelay < 0)
# Block which fulfills the request
operation = proc do
sleep delay
if path.match(/.js$/)
resp.status = 200
resp.headers["Content-Type"] = "text/javascript"
resp.content = "(function(){
var start = new Date();
while(new Date() - start < #{jsdelay}){}
})();"
end
if path.match(/.css$/)
resp.status = 200
resp.headers["Content-Type"] = "text/css"
resp.content = "body {font-size: 50px;}"
end
end
# Callback block to execute once the request is fulfilled
callback = proc do |res|
resp.send_response
end
# Let the thread pool (20 Ruby threads) handle request
EM.defer(operation, callback)
end
end
EventMachine::run {
EventMachine::start_server("0.0.0.0", 8081, Handler)
puts "Listening..."
}
上面的迷你服务器允许我为JavaScript文件(服务器和客户端)设置任意延迟,以及任意CSS延迟.例如,http://10.0.0.50:8081/test.css?delay=500
让我在传输CSS时延迟500毫秒.
我使用下面的页面进行测试.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type='text/javascript'>
var startTime = new Date();
</script>
<link href="http://10.0.0.50:8081/test.css?delay=500" type="text/css" rel="stylesheet">
<script type="text/javascript" src="http://10.0.0.50:8081/test2.js?delay=400&jsdelay=1000"></script>
</head>
<body>
<p>
Elapsed time is:
<script type='text/javascript'>
document.write(new Date() - startTime);
</script>
</p>
</body>
</html>
当我首先包含CSS时,页面需要1.5秒来呈现:
当我首先包含JavaScript时,页面需要1.4秒来呈现:
我在Chrome、Firefox和Internet Explorer上也得到了类似的结果.然而,在歌剧中,顺序根本不重要.
似乎正在发生的是,JavaScript解释器拒绝启动,直到所有CSS都下载完毕.因此,随着JavaScript线程获得更多的运行时间,让JavaScript includes first更有效.
我是否遗漏了什么,将CSS包含放在JavaScript包含之前的建议是否不正确?
很明显,我们可以添加async,或者使用setTimeout释放渲染线程,或者将JavaScript代码放入页脚,或者使用JavaScript加载程序.这里的重点是关于基本JavaScript位和CSS位在头部的顺序