Skip to content

Instantly share code, notes, and snippets.

@centminmod
Forked from tomjn/tomjn_http2_push.php
Created February 4, 2019 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save centminmod/ccf35fc77995730c0737006544885279 to your computer and use it in GitHub Desktop.
Save centminmod/ccf35fc77995730c0737006544885279 to your computer and use it in GitHub Desktop.
A naive and incomplete, but functional approach to http2 push
<?php
/**
* Plugin name: HTTP2 Push scripts
* Author: Tom J Nowell
*/
function tomjn_get_dep_url( /*\WP_Dependency*/ $dep ) {
global $wp_version;
$relative = str_replace( site_url(), '', $dep->src );
$ver = $dep->ver;
if ( $ver === false ) {
$ver = $wp_version;
}
return $relative.'?ver='.$ver;
}
function tomjn_push_scripts() {
global $wp_scripts, $wp_styles;
foreach ( $wp_scripts->queue as $handle ) {
header("Link: <".tomjn_get_dep_url( $wp_scripts->registered[$handle] ).">; rel=preload; as=script", false);
}
}
function tomjn_push_styles() {
global $wp_styles;
foreach ( $wp_styles->queue as $handle ) {
header("Link: <".tomjn_get_dep_url( $wp_styles->registered[$handle] ).">; rel=preload; as=style", false);
}
}
add_action( 'wp_enqueue_scripts', 'tomjn_push_scripts', PHP_INT_MAX );
add_action( 'wp_enqueue_scripts', 'tomjn_push_styles', PHP_INT_MAX );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment