Mastering HTML5 Prefetching

by Jean. 19 Comments -

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!

Comments (19) - Leave yours

  1. Tait Brown said:

    It’s a shame there isn’t a Modernizr test yet for prefetch/prerender, because that would be good to build into your code.

    I would probably suggest you rewrite your snippet as a jQuery plugin, as your code is polluting the global namespace. While I know “app” is just a template, it’s also one of the most used variables when trying to avoid polluting namespaces. Anyway, if It’s already dependant upon jQuery, it makes sense to build it in as a plugin. No variables!

    • Greg said:

      I agree that it should be a plugin, but I disagree that it’s ‘pollution’ of the global namespace. By namespacing it as “app” (or whatever, like you I think it’s just showing a placeholder name) you’re only adding one variable to the global namespace. This practice is within the realm of the good, and therefore not really “pollution”. If a developer already had an “app”, this would just become “app.prefetchamatizer”, no more a pollution than “$.prefetchamatizer”. Pollution would be the two functions just being added without any namespacing at all.

  2. Bjorn van der Neut said:

    So If i have like 10 interesting links on my homepage I want to prefetch I can do that like this?

    etc.

    and of course than also 10 times with prerender.

    And is it necessarily that you have the correct document type? I have now:
    link rel=prefetch href=http://www.example.com/page1.html

  3. J.Logan said:

    I haven’t tried to use this yet, but I find it to be an interesting idea.

    But I had the thought – if you’re fetching next and previous posts….and then each of those posts fetches its next and previous posts…..and then each of those fetches….and so on and so forth. Is a visitor potentially downloading your entire archive while reading an article? Or does this only go one level and stop?

  4. Eric Bidelman said:

    Prefetching and Prerendering are a bit different.

    Prefetching
    is a feature that is currently implemented in Firefox. It allows site authors to include a link tag in their HTML that instructs the browser to begin fetching a given URL. When it encounters the tag, the browser fetches the top-level resource at that URL (most often an HTML page). Prefetching, however, often does not lead to user-noticeable speed-ups because most of the content is in sub-resources, such as JavaScript, CSS, and media files. Also, in some cases the sub-resources aren’t even part of the HTML as provided by the server, and are only inserted via scripts when the page loads.

    Prerendering
    extends the concept of prefetching. Instead of just downloading the top-level resource, it does all of the work necessary to show the page to the user—without actually showing it until the user clicks. Prerendering behaves similarly to if a user middle-clicked on a link on a page (opening it in a background tab) and then later switched to that tab. However, in prerendering, that “background tab” is totally hidden from the user, and when the user clicks, its contents are seamlessly swapped into the same tab the user was viewing. From the user’s perspective, the page simply loads much faster than before.

    http://code.google.com/chrome/whitepapers/prerender.html

  5. Agadir said:

    another new technique to made browsing the web easy, i will use it in my website, but the question is, is it possible to use it in non HTML5 website?

  6. Nate said:

    I’m trying with no avail to get this working. In Chrome’s inspector it throws up failed get requests for the URL i’m trying to use the rel=prerender.

  7. Colin Dean said:

    Something to consider is a warning that came out when prefetching first became popular, I believe in a Firefox plugin which became the basis of the prefetch capability.

    If you provide prefetching/prerendering, you’d better have the capacity to sustain it and the careful planning of what content should be marked for these. If your visitors don’t often venture past the first page, you should not ever prefetch/prerender because you’ll be putting an unnecessary load on your site. You really should only consider prefetching/prerendering if almost all of your visitors proceed to the page which is prefetched/preloaded. Look at your traffic stats to see if it’s worth it.

  8. drublic said:

    Thanks for this great article.

    If you think semantics are important – and I do – please be aware that the prefetch-class is Not pretty semantic though.

  9. Casha R said:

    Although I’ve heard of HTML 5.0, this is the first time I’ve heard the term “prefetching”. The only thing is, can it be used to return and alternative webpage instead of the webpage the viewer thinks they’re going to see? For example, if I went to a website such as NBC.com and instead of loading the NBC.com homepage (like I would expect them to) I am instead led to a webpage that’s purely an advertisement.

    What am I missing here? Please explain (somebody… anybody)

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!