Make the browser preconnect to a domain via javascript



Published: 2019-08-14 09:05:10 +0000
Categories: Javascript,

Language

Javascript

Description

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)

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);

License

BSD-3-Clause

Keywords

js, preconnect, prefetch, preload, dns-prefetch, resource hints, dynamic,

Latest Posts


Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, yr4pnhounvdybotb.onion and snippets.6zdgh5a5e6zpchdz.onion