HTTP/2 Roundtrip and Preconnect

Advertisement

Previously we talked about Optimizing Nginx HTTP/2 TLS. W3C defines dns-prefetch, preconnect, prefetch & prerender. In this article we will discussed the practical scenario of HTTP/2 Roundtrip and Preconnect usage. The concept of Preconnect is simple. We often know about resources the browser is likely to need before the browser does. Preconnect involves resolving the DNS name, perform the TCP handshake, and negotiate the TLS tunnel in a non-blocking way before the specific resource’s turns come. W3C specification can be read here :

Vim

1

http://w3c.github.io/resource-hints/#preconnect

HTTP/2 Roundtrip and Preconnect : Example

Most of the modern browsers anticipate what connections the site will need before the request is made. Anticipating can eliminate the DNS, TCP, and TLS roundtrips before the actual request. But the browsers are cannot reliably predict all the preconnect targets for every website. We can tell the browser which sockets we will need via preconnect hint. This is an example webpagetest of our website where Preconnect has been used :

Advertisement

---

With the preconnect hint in our markup, the browser begins the socket setup in parallel, completes it ahead of time, and allows the requests to be sent immediately – in particular scenario, preconnect can virtually remove the round trip delay from the critical path and eliminate latency.

HTTP/2 Roundtrip and Preconnect : Codes and Snippets

pr=”1.00″ means 100% chance. It can be 0.75, 0.50 etc. We need to add these before the HTML markup of the actual request, that simply means on the header.

Instead of the previous approach, we can invoke preconnect in response to user input or anticipated activity with JavaScript (adapted from igvita.com) :

Vim

1

2

3

4

5

6

7

8

<script>

functionpreconnectTo(url){

varhint=document.createElement("link");

hint.rel="preconnect";

hint.href=url;

document.head.appendChild(hint);

}

</script>

Adding the above script to footer or in body eliminates the extra HTML on above the fold.

Conclusion

Preconnect can be useful if rightly used. Check performance with WebPageTest and Google PageSpeed Insights against your each settings/usage. Preconnect can waste time if wrongly used or just create a placebo effect.