Make the browser preconnect to a domain via javascript (Javascript)

A little while ago, 3 new candidates were put forward - Preload, Preconnect and Prefetch - known collectively as Resource Hints.

Embedding these into a HTML base page is straight-forward and well documented. But, what if you need to do something different?

In MISC-35 I decided to embed a search box into various sites (for example, this one) that would take the user to a third party search engine with a site: operator prepended to the query

The only problem was, that the search would take longer than comfortable to run, as upon hitting "Search" the browser would need to resolve DNS, connect, do a HTTPS handshake and then place the necessary request

It's possible to work around this though, by using the preconnect hint. I didn't want the user's browser to pre-connect every time they loaded a page, so wanted it gated on whether they were interacting with the search box itself

This snipper shows how to use Javascript to tell a modern browser to preconnect to a specific service (the exact URL doesn't matter, only the protocol and hostname)

Although I've not (yet) had cause to do so, you can use the same technique with preload and prefetch too (as well as their subtypes like dns-prefetch)

Details

Snippet

// Create a new element with the preconnect URL in
var l = document.createElement('link');
l.rel = 'preconnect';
l.href = "[scheme]://[hostname]"; // Replace this with the service to preconnect to
document.head.appendChild(l); // Browser will now establish a connection

Usage Example

function setupPreConnect(){
    // We wrap in a conditional so we're not spamming the DOM with every keypress
    if (!window.ecosiapreconnected){

        // The user has started typing in the text box, so take that as a sign we're going to be going to Ecosia.
        // Tell the browser to pre-connect to speed up the response
        var l = document.createElement('link');
        l.rel = 'preconnect';
        l.href = "https://www.ecosia.org";
        document.head.appendChild(l);

        // Set a variable so we don't inject a new element if they press another key 
        window.ecosiapreconnected = 1;
    }
}

// Trigger the preconnect once a user starts typing in the search box
document.getElementById('searchbox').addEventListener('keypress',setupPreConnect);

// If you'd prefer, you could do it when the searchbox is brought into focus
// document.getElementById('searchbox').addEventListener('focus',setupPreConnect);