Prerendering first post in your home – WordPress

Have you heard about link prefetching?

It's a browser mechanism that Firefox implemented time ago, it allows you to prefetch files and resources in the background.

What for?

It should be used to load resources that the user will load on the next click. Say you have a landing page with a link that the user will likely click on, we could prefetch resources for the next page before the click. By doing so the user will already have them and the next page will load a lot faster instantly.

Google Chrome has gone even further with a new concept: prerendering.

Extending the concept of prefetching

With prerendering we can load the whole page (resources, html...) on the background for the user. In fact, this is something Google is being doing on his search result for a while.

Chrome only

Right now this feature is Chrome only but even so it's something worth exploring.

Open a tab on your Chrome: chrome://net-internals/#prerender

Here you can see if any page has been page prerendered or requested for prerendering. You can test if your browser has the option enabled by doing a search on Google. You'd probably see the first result prerendered on that Chrome information page.

What could prevent prerendering?

There's always a "but", here's the list from the Web Developer's Guide:

  • The user is using a version of Chrome where prerendering is not enabled by default.
  • The user has disabled prerendering by unchecking "Predict network actions to improve page load performance" in Settings.
  • Another page is already being prerendered. Chrome will only prerender at max one URL per instance of Chrome (not one per tab). This limit may change in the future in some cases.
  • There are multiple prerender directives on the page, in which case which prerender directive is taken and which is ignored is undefined (depending on the timing of when the directives were encountered).
  • Chrome encountered another prerender directive within the last 500 ms.
  • The user is browsing in an incognito window
  • The prerender is aborted based on a situation caused by the receiving page. See "Situations in which prerendering is aborted".

I'm sold, how do I do it with WordPress?

Alright, open your theme's header.php file and paste the following code.

As you can see I've added the condition so it'll only run on the home page, where the user is very likely to click on the first post.

<?php if( is_home() ){ $first_post_args = array( 'numberposts' => 1, 'orderby' => 'post_date', 'order' => 'DESC' ); $first_post_array = get_posts( $first_post_args ); foreach ( $first_post_array as $first_post ) : setup_postdata( $first_post ); ?> <link rel="prerender" href="<?php the_permalink(); ?>" /> <?php endforeach; wp_reset_postdata(); } ?>
Code language: HTML, XML (xml)

More information about prerender on the Web Developer's Guide to Prerendering in Chrome.

Leave a Reply

Add <code> Some Code </code> if you need to.