HTTP2 Push- placing script tags in res.end

2019-08-15 10:28发布

问题:

After reading HTTP2 Article using Speedy NPM module, I have a question.

The benefit of HTTP2 push is that the browser has the resources cached before the browser requests them.

In this example:

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

What does <script src="/main.js"></script> actually cause the browser to do in res.end('Hello World! <script src="/main.js"></script>')?

And if the index.html has <script src="/main.js"></script> inside of it, why place it in res.end('Hello World! <script src="/main.js"></script>')?

回答1:

res.end('Hello World! <script src="/main.js"></script>'); is sending a very minimal web page. (It is missing <html><head><body> etc..., because it's a bare-bones example.) It looks like this:

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

The web page displays "Hello World!" but you wouldn't see the <script> tag rendered. The browser parses the "web page", processes the link to main.js and discovers it already received that file (from the .push). Finally that script is executed and opens an alert().

main.js was preemptively sent even before the "web page" content was delivered, that's the res.push('/main.js',...).