Preload Pages or Posts in WordPress using HTML5 Link Prefetching

Advertisement

There are a lots and tons of way to faster your site load by using .htacess, CSS Sprites, Image Optimization, Javascript file compression and so on, the known way is by using CDN. Firefox introduces a new strategy for website optimization: link prefetching.

What is link prefetching? From the MDN

Link prefetching is a browser mechanism, which utilizes browser idle time to download or prefetch documents that the user might visit in the near future. A web page provides a set of prefetching hints to the browser, and after the browser is finished loading the page, it begins silently prefetching specified documents and stores them in its cache. When the user visits one of the prefetched documents, it can be served up quickly out of the browser’s cache.

That really sounds cool, it silently download specified pages and stores theme into cache so next time you visit that page it load as lighting fast. It’s very to implement and only a line of code.

Tag

HTML5 prefetching is done via the LINK tag, specifying “prefetch” as the rel and the href being the path to the document.


<!—full page-->
<link rel="prefetch" href="/how-to-create-fixed-menu-when-scrolling-page-with-css-and-jquery/">

<!—image only -->
<link rel="prefetch" href="/images/big.jpeg">

WordPress Code

Add this code before the closing head tag


<!-- prefetch and prerender page -->
<?php
// this check if we're in category archive page and paged is greater than 1
if ( is_category() && ( $paged > 1 ) && ( $paged < $wp_query->max_num_pages )) { ?>
	<link rel="prefetch" href="<?php echo get_next_posts_page_link(); ?>">
	<link rel="prerender" href="<?php echo get_next_posts_page_link(); ?>">
<?php } elseif (is_singular()) {
	// get previous post permalink
	$prev_post_link = get_permalink(get_adjacent_post(false,'',false));
	// get next post permalink
	$next_post_link = get_permalink(get_adjacent_post(false,'',true));
	if( $next_post_link != get_permalink() )
		$post_link = $next_post_link;
	else
		$post_link = get_bloginfo('url');
	?>
	<link rel="prefetch" href="<?php echo $post_link; ?>">
	<link rel="prerender" href="<?php echo $post_link; ?>">
	<link rel="next" href="<?php echo $prev_post_link; ?>">
<?php } ?>

Happy coding ^_^

Advertisement