Skip to content

February 3, 2011

Prefetching Javascript and CSS

Prefetching javascript and CSS files can improve the page load times as users navigate your site.  This creates a better user experience and may even improve your search engine rankings.

I’ll describe an easy prefetch technique useful in situations in which you are reasonably sure the user will navigate from Page A to Page B.  This situation typically involves the user filling out a form.  Chances are high that if a user begins to fill out a form, she will eventually submit it, arriving at Page B.  If you prefetch resources that will be needed by Page B, it’ll load faster when the user navigates to it.  This is a technique I’m using on our lifespan test.

I use jQuery here. It’s not necessary to use jQuery, however it makes life easier.

$(':input[name="q12"]').change(function() {
    var e = document.createElement('script');
    e.async = true;
    e.src = "";
    e = document.createElement('link');
    e.type = "text/css";
    e.rel = "stylesheet";
    e.href = "";

I’m only using jQuery here to bind some code to the “change” event on the form field with name “q12” (which happens to be Question 12 of 18 on the Lifespan Test).  The above snippet is inside of a jQuery document ready handler.  The idea here is that when the user has gotten to Question 12, we can be quite sure she will complete the form, and so we can go ahead and prefetch resources needed for the next page.

When the value of form field “q12” changes, I prefetch javascript files by creating “script” tags and CSS files by creating “link” tags. On Line 3, I set the async attribute. This new HTML5 attribute, which browsers are beginning to support, is useful because async’d scripts will not block other resources from downloading.  It is not strictly necessary in this case, but I’ve included because it is becoming a standard idiom for asynchronous scripts.

On Lines 5 and 11 I append the script and link tags to a div with id “pf”.  This is just an empty div tag I’ve included at the bottom of the page.  Finally, on Line 13, the code unbinds itself from the change event, ensuring that it only runs once.

Because the server sends these prefetched files with appropriate cache control headers, the browser will cache them, and they will be immediately available when needed on other pages.  When the user submits the form, the next page will load more quickly because the prefetched files are now in the browser’s cache.  Ultimately, we all want to create a better user experience for our visitors, and ensuring fast page load times helps to deliver that experience.

Share your thoughts, post a comment.


Note: HTML is allowed. Your email address will never be published.

Subscribe to comments