2015-11-03 72 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',...)