Search code examples
htmlpagespeedweb-performance

Using rel=preconnect for both http and https resources from the same domain


I'm currently working on a web project and am looking for advice in relation to pre-connecting to a domain for sub-resources.

My assumption is that ideally, all of the sub-resources should be served from the domain using the same protocol, thus saving round-trips to the server. However, in some areas of the code I'm working from, some resources are being loaded via http and in other areas, the resources are being loaded via https.

For the purpose of this question, please imagine that I don't have access to some sections of the code.

To get the benefits of pre-connecting, (in the time between now and liaising with others to use the same route), would it be better to include:

<link rel="preconnect" href="http://www.example.com" />
<link rel="preconnect" href="https://www.example.com" />

Or use the following protocol-relative URL:

<link rel="preconnect" href="//www.example.com" />

Solution

  • You need to preconnect to both protocols because they are considered as two different domains by the browser:

    <link rel="preconnect" href="http://www.example.com" />
    <link rel="preconnect" href="https://www.example.com" />
    

    If you want to go further, I would also recommend the use of dns-prefetch, for browsers that can't currently handle preconnect. So it would look like:

    <link rel="preconnect" href="http://www.example.com" />
    <link rel="dns-prefetch" href="http://www.example.com" />
    <link rel="preconnect" href="https://www.example.com" />
    <link rel="dns-prefetch" href="https://www.example.com" />