Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,37 @@ public function get_html(): string {
return implode( '', $link_tags );
}

/**
* Gets the HTTP Link header string.
Comment thread
AhmarZaidi marked this conversation as resolved.
Outdated
*
* @return string HTTP Link header.
Comment thread
AhmarZaidi marked this conversation as resolved.
Outdated
*/
public function get_headers(): string {
Comment thread
AhmarZaidi marked this conversation as resolved.
Outdated
Comment thread
AhmarZaidi marked this conversation as resolved.
Outdated
$link_headers = array();

foreach ( $this->get_adjacent_deduplicated_links() as $link ) {
Comment thread
AhmarZaidi marked this conversation as resolved.
Outdated
$media_features = array( 'screen' );
if ( null !== $link['minimum_viewport_width'] && $link['minimum_viewport_width'] > 0 ) {
$media_features[] = sprintf( '(min-width: %dpx)', $link['minimum_viewport_width'] );
}
if ( null !== $link['maximum_viewport_width'] && PHP_INT_MAX !== $link['maximum_viewport_width'] ) {
$media_features[] = sprintf( '(max-width: %dpx)', $link['maximum_viewport_width'] );
}
$link['attributes']['media'] = implode( ' and ', $media_features );

$link_header = '<' . esc_url( $link['attributes']['href'] ?? '' ) . '>; rel="preload"';
Comment thread
AhmarZaidi marked this conversation as resolved.
Outdated
foreach ( $link['attributes'] as $name => $value ) {
if ( 'href' !== $name ) {
$link_header .= sprintf( '; %s="%s"', $name, esc_attr( $value ) );
Comment thread
AhmarZaidi marked this conversation as resolved.
Outdated
}
}

$link_headers[] = $link_header;
}

Comment thread
AhmarZaidi marked this conversation as resolved.
return 'Link: ' . implode( ', ', $link_headers );
}

/**
* Counts the links.
*
Expand Down
5 changes: 5 additions & 0 deletions plugins/optimization-detective/optimization.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,11 @@ function od_optimize_template_output_buffer( string $buffer ): string {

$tag_visitor_registry = new OD_Tag_Visitor_Registry();

// Send any preload links as Link headers.
if ( count( $preload_links ) > 0 && ! headers_sent() ) {
header( $preload_links->get_headers() );
}

Comment thread
AhmarZaidi marked this conversation as resolved.
Outdated
/**
* Fires to register tag visitors before walking over the document to perform optimizations.
*
Expand Down