HTTP2推送脚本标签在res.end
使用Speedy NPM模块阅读HTTP2文章后,我有一个问题。
HTTP2推送的好处是浏览器在浏览器请求之前caching资源。
在这个例子中:
spdy.createServer(options, function(req, res) { // push JavaScript asset (/main.js) to the client res.push('/main.js', {'content-type': 'application/javascript'}, function(err, stream) { stream.end('alert("hello from push stream!")'); }); // write main response body and terminate stream res.end('Hello World! <script src="/main.js"></script>'); }).listen(443);
什么<script src="/main.js"></script>
实际上导致浏览器在res.end('Hello World! <script src="/main.js"></script>')
?
如果index.html里面有<script src="/main.js"></script>
,为什么把它放在res.end('Hello World! <script src="/main.js"></script>')
?
res.end('Hello World! <script src="/main.js"></script>');
正在发送一个非常小的网页。 (它缺less<html><head><body> etc...
,因为它是一个简单的例子。)它看起来像这样:
Hello World! <script src="/main.js"></script>
网页显示“Hello World!” 但是你不会看到呈现的<script>
标记。 浏览器parsing“网页”,处理到main.js
的链接并发现它已经接收到该文件(来自.push
)。 最后,脚本被执行并打开一个alert()
。
在“网页”内容交付之前, main.js
被抢先发送,这就是res.push('/main.js',...)
。