HTTP2在res.end中推送脚本标签

时间:2015-11-03 23:39:00

标签: node.js spdy http2

阅读HTTP2 Article using Speedy NPM module后,我有一个问题。

HTTP2推送的好处是浏览器在浏览器请求之前缓存了资源。

在这个例子中:

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>')

1 个答案:

答案 0 :(得分:1)

res.end('Hello World! <script src="/main.js"></script>');正在发送一个非常小的网页。 (它缺少<html><head><body> etc...,因为它是一个简单的例子。)看起来像这样:

Hello World!
<script src="/main.js"></script>

网页显示“Hello World!”但你不会看到呈现的<script>标签。浏览器解析“网页”,处理指向main.js的链接并发现它已收到该文件(来自.push)。最后执行该脚本并打开alert()

main.js甚至在“网页”内容发布之前就被预先发送,即res.push('/main.js',...)

相关问题