HomeMethod

Knowledge

Web VitalsTechniquesSnippetsAnswersImpactsBottlenecks

Preconnect to third-party origins

  • Performance

Every request to a third-party origin (fonts, analytics, CDNs) requires a DNS lookup, TCP handshake, and TLS negotiation before a single byte is transferred. That’s 100-300ms of dead time per origin.

Preconnect resource hints tell the browser to establish these connections early, before it even discovers the resources in the HTML or CSS:

preconnect-origins.php
<?php
/**
 * Preconnect to Third-Party Origins
 *
 * Adds preconnect resource hints for third-party domains your site depends on.
 * This establishes early connections (DNS + TCP + TLS) before the browser
 * discovers the resources, shaving 100-300ms off each origin's first request.
 * Only preconnect to origins used on most pages — overuse hurts performance.
 *
 * Usage: Add to functions.php. Replace the URLs with your actual third-party origins.
 *
 * @category performance
 * @language php

 *
 * @author Adame Dahmani https://adame.io
 * @support Support my family project: https://adame.io/fundraiser
 */
add_filter( 'wp_resource_hints', function ( $urls, $relation_type ) {
    if ( $relation_type === 'preconnect' ) {
        $urls[] = [
            'href'        => 'https://fonts.googleapis.com',
            'crossorigin' => true,
        ];
        $urls[] = [
            'href'        => 'https://fonts.gstatic.com',
            'crossorigin' => true,
        ];
    }
    return $urls;
}, 10, 2 );

Only preconnect to origins used on most pages. Each preconnect consumes a connection slot — overdoing it wastes resources on connections that may not be used.

Support our family now