HTML5 Zone is brought to you in partnership with:

My name is Jean-Baptiste Jung and I’m a 29 years old web developer and professional blogger. I was born and raised in Paris, France and I now live in Belgium with my wife and our adorable cat. I first used the internet in 1998, built my first website in 2001 and finally started to work as a professional web developer in 2005. In 2010, I left my job and created my own web development studio. jb is a DZone MVB and is not an employee of DZone and has posted 55 posts at DZone. You can read more from them at their website. View Full User Profile

Mastering HTML5 Prefetching

01.23.2012
| 5078 views |
  • submit to reddit

Among other great features, HTML5 introduces prefetching, the art of loading pages before the user requested them. In this article, I’m going to discuss this new technique as well as showing you some ready to use examples to drastically improve your website loading time.

What is prefetching, and why it is useful

According to whatwg.org, rel=prefetch "indicates that preemptively fetching and caching the specified resource is likely to be beneficial, as it is highly likely that the user will require this resource." Search engines sometimes add <link rel=prefetch href="URL of top search result"> to the search results page if they feel that the top result is wildly more popular than any other.
For example: using Firefox, search Google for CNN; view source; search for the keyword "prefetch".

As loading time is a very important factor of a website quality, prefetching can definitely improve the user experience by loading pages before the user actually requested them. Of course, you have to be careful (Don’t prefetch your entire website!) but prefetching is definitely a feature that will make the web a better place.

Prefetching pages with HTML5

Prefetching pages is super easy to implement. The only thing you have to do is to place the following code with the <head> and </head> tags of your page. The href attribute have to contain the url of the page to prefetch.

<link rel="prefetch" href="http://www.example.com/">

It is also possible to prefetch only an image:

<link rel="prefetch" href="http://www.catswhocode.com/wp-content/uploads/my_image.png">

Browser support

As prefetching (Or prerendering as Google Chrome name that feature) is a part of HTML5, it is currently not supported in all browsers:

  • Mozilla Firefox: Supported
  • Google Chrome: Supported since version 13 (Use an alternate syntax)
  • Safari: Currently not supported
  • Internet Explorer: Currently not supported

So, should you use it now? In my humble opinion, the answer is a definitive yes: Using prefetching now is possible in both Firefox and Chrome, and other browsers will probably implement it very soon.

Also, if you use prefetching on your website and the visitor browser do not support prefetching, nothing will happen. For what I’ve seen during some personal tests, it is safe to use prefetching as browsers will either implement it, or completely ignore it.

Another thing to note is that Google Chrome do not use the prefetch attribute and use prerender instead. This means that you have to implement both prefetch and prerender, as shown in the example below:

<link rel="prefetch" href="http://www.example.com/"> <!-- Firefox -->
<link rel="prerender" href="http://www.example.com/"> <!-- Chrome -->

Prefetching pages on your WordPress blog

As I know most of my readers are WordPress users, I thought about a WordPress-specific example of HTML5 prefetching. A blog is typically the kind of website where prefetching can be very useful: On many situations, it is possible to “guess” which page the visitor will want to read next.

For example, if a visitor is currently having a look to the second page of your archives, it is highly possible that he’ll read the third page next. The following code snippet (Courtesy of Bernd) is ready to use: Just paste it into the header.php file of your theme in order to prefetch next archive pages.

<?php if (is_archive() && ($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 } ?>

Of course, the version above can be enhanced according to your site own needs. According to my analytics, most people comes to my site on an article page like this one, and then, have a look to the home page. So, it can be great to add a new condition to the code above and prefetch the home page when the visitor is reading an article.

<?php if (is_archive() && ($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()) { ?>
<link rel="prefetch" href="<?php bloginfo('home'); ?>">
<link rel="prerender" href="<?php bloginfo('home'); ?>">
<?php } ?>

Prefetching using jQuery

Now that we saw what prefetching can do for you, what about using jQuery to automatically prefetch each link with the prefetch class? That’s exactly what the snippet below do. Simply paste it to your website, and then add a prefetch class to each link you’d like to prefetch.

// create an object named "app" which we can define methods on
var app = {
    // returns an array of each url to prefetch
    prefetchLinks: function(){
        // returns an array of each a.prefetch link's href
        var hrefs = $("a.prefetch").map(function(index, domElement){
            return $(this).attr("href");
        });
        // returns the array of hrefs without duplicates
        return $.unique(hrefs);
    },

    // adds a link tag to the document head for each of prefetchLinks()
    addPrefetchTags: function(){
        // for each prefetchLinks() ...
        this.prefetchLinks().each(function(index,Element){
            // create a link element...
            $("<link />", {
                // with rel=prefetch and href=Element...
                rel: "prefetch", href: Element
                // and append it to the end of the document head
            }).appendTo("head");
        });
    },
}
// when the document is ready...
jQuery(function(){
  // call the method we defined above.
    app.addPrefetchTags();
}

Thanks to Gavin Morrice for this great snippet!

 

Source: http://www.catswhocode.com/blog/mastering-html5-prefetching

 

Published at DZone with permission of jb j, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)