Prefetch the Next Page of Archives and Paginated Posts
Adds a prefetch hint for the next page of blog archives, category pages and multi-page posts, so it opens almost instantly when visitors click "Next".
Opens WPIDE on
Code
add_action( 'wp_head', function () {
global $wp_query, $page, $numpages;
$next = '';
if ( ( is_home() || is_archive() || is_search() ) && get_query_var( 'paged', 1 ) < (int) $wp_query->max_num_pages ) {
$next = get_next_posts_page_link();
} elseif ( is_singular() && $numpages > 1 && $page < $numpages ) {
$next = _wp_link_page( $page + 1 );
$next = preg_match( '#href="([^"]+)"#', $next, $m ) ? $m[1] : '';
}
if ( $next ) {
printf( "<script>if(!(navigator.connection&&navigator.connection.saveData)){var l=document.createElement('link');l.rel='prefetch';l.href=%s;document.head.appendChild(l);}</script>\n", wp_json_encode( esc_url_raw( $next ) ) );
}
}, 20 );
Notes
Prefetching uses a little extra bandwidth for visitors who never click; it is skipped for visitors with data saver turned on.
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.