2015-11-03 32 views
1

在阅读HTTP2 Article using Speedy NPM module后,我有一个问题。HTTP2推送脚本标签在res.end

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

我对此也很感兴趣。有人问我是否在[此SO问题]中的文档中添加资源(http://stackoverflow.com/questions/34049872/http2-spdy-push-stream-verification-how-to-test#comment55854460_34049872)。 – CelticParser

回答

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