Preload Key Scripts and Stylesheets by Handle
Adds preload hints for the enqueued scripts and stylesheets you name, so the browser fetches files that are discovered late (such as a slider script or icon font CSS) right at the start of the page load.
Opens WPIDE on
Code
// Handles to preload: 'script' or 'style'.
$wpide_preload_handles = array(
'swiper' => 'script',
'font-awesome' => 'style',
);
add_filter( 'wp_preload_resources', function ( $resources ) use ( $wpide_preload_handles ) {
foreach ( $wpide_preload_handles as $handle => $type ) {
$registry = 'script' === $type ? wp_scripts() : wp_styles();
if ( empty( $registry->registered[ $handle ] ) || ! in_array( $handle, $registry->queue, true ) || ! $registry->registered[ $handle ]->src ) {
continue;
}
$item = $registry->registered[ $handle ];
$src = $item->src;
if ( ! preg_match( '#^(https?:)?//#', $src ) ) {
$src = $registry->base_url . $src;
}
$ver = $item->ver ? $item->ver : $registry->default_version;
$resources[] = array(
'href' => add_query_arg( 'ver', $ver, $src ),
'as' => 'script' === $type ? 'script' : 'style',
);
}
return $resources;
} );
Notes
Only handles that are actually enqueued on the current page are preloaded; preloading too much slows down more important files.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.