Skip to main content
Robert Michalski

How to add preconnect links to head tag in WordPress

Whenever the browser makes a connection to fetch a file or call an API, the domain of those URLs must be resolved to IP addresses which involves making DNS lookups. Nowadays HTTPS is used by default which involves establishing secure TLS connections as well.

This requires several network round-trips, first resolving the DNS to IP and then establishing secure TLS connections.

The browser does this whenever javascript, css, or fonts are requested, before the actual files are requested. There is a way to give hints to the browser, that resources are going to be needed soon, so it can perform DNS lookup and initiate TLS connections before the actual files are requested. So when it's time to actually request the files and make API calls, no extra round-trips are needed.

This can improve the loading speed of websites.

For instance adding domains for Google Analytics or third-party APIs that are used heavily.

How to add preconnect hints in WordPress #

Customize the code below and add it as a plugin or mu-plugin, see this guide.

The dns-prefetch entry is for older browsers that do not support preconnects.

    add_action('wp_head', 'YOUR_PREFIX_add_preconnect_links', 5);

    function YOUR_PREFIX_add_preconnect_links() {
        $domains = [
            // Cloudflare analytics
            'static.cloudflareinsights.com',
            // Google tracking
            'www.googletagmanager.com',
            'www.google-analytics.com',
            'stats.g.doubleclick.net',
            // Monsterinsights
            'a.opmnstr.com',
            'a.omappapi.com',
            'api.omappapi.com',
        ];
        foreach ($domains as $domain) {
            ?>
            <link rel="preconnect" href="<?php echo $domain; ?>" crossorigin>
            <link rel="dns-prefetch" href="<?php echo $domain; ?>">
            <?php
        }
    }
}