HTTP2 Push- placing script tags in res.end

有些话、适合烂在心里 提交于 2019-12-11 05:42:59

问题


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



来源:https://stackoverflow.com/questions/33511203/http2-push-placing-script-tags-in-res-end

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!