Skip to content

Instantly share code, notes, and snippets.

@tomjn
Created January 25, 2019 23:43
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tomjn/7fe22a4ec20f2565004bd216e9d1f497 to your computer and use it in GitHub Desktop.
Save tomjn/7fe22a4ec20f2565004bd216e9d1f497 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