Lawrence Gosset Menu

Responsive performance

Recently I’ve had my responsive thinking cap on and have been experimenting beyond the CSS sheet. By shifting my focus onto performance, I’ve been able to get a feel for how improving it can transform the experience.

By definition, when something responds, it reacts quickly and positively. Performance is big business that can cost companies millions for just a mere 100ms in page speed loss. It came as a shock to me when Tim Kadlec measured a highly regarded responsive site to have taken a whopping 93 seconds to load over a 3G connection. It consisted of 105 requests weighing in at 5,942kB.

It’s this kind of thing that is the polar opposite of responsive.

Flexible images, percentage widths and media queries are all key ingredients of a responsive site — but it shouldn’t stop there. Performance needs to embraced as a guiding principle, instead of an afterthought. Snappy websites create positive experiences, and that’s good for business.

During the build process of this site, I’ve jumped between the front and back-ends, with the aim of cutting as many milliseconds and kBs off the page load. Although this website is small and lightweight, the principles and best practices are valuable and can be applied to something larger in scale.

Initial payload

The most important performance consideration for me was the initial kB payload. When a page loads, the bare essentials should be delivered, and the rest progressively enhanced. For example, my base is made up of:

Beyond that, my web fonts are loaded asynchronously, and demo page assets kept separate.

Async the web fonts

I’ve used Typekit’s async snippet to load web fonts conditionally based off of a Modernizr.load (aka yeynope) @font-face test. Put simply, I’m only loading web fonts in browsers that can actually display them.

By loading asynchronously, initial overhead is cut down and potential JavaScript blocking avoided.

Here’s the code snippet:

Modernizr.load([{
  test: Modernizr.fontface,
  complete: function() {
    TypekitConfig = {
      kitId: 'xxxxxxx',
      scriptTimeout: 3000
    };
    (function() {
      var t = setTimeout(function() {
      }, TypekitConfig.scriptTimeout);
      var tk = document.createElement('script');
      tk.src = '//use.typekit.com/' + TypekitConfig.kitId + '.js';
      tk.onload = tk.onreadystatechange = function() {
        var rs = this.readyState;
        if (rs && rs != 'complete' && rs != 'loaded') return;
        clearTimeout(t);
        try { Typekit.load(TypekitConfig); } catch (e) {}
      };
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(tk, s);
    })();
  }
}]);

The downside to this is that the fonts are only downloaded once the main JavaScript file has been parsed, which causes a ~500ms delay (on desktop).

‘One page’ with pushState

I’m using Turbolinks on this site, which takes advantage of the HTML5 history API’s pushState and replaceState methods. They allow you to replace the content of the <body>, whilst keeping all the <head> assets in tact. This performs a page load illusion by changing the URL and title dynamically, whilst pushing the new page onto the browser history stack. I like to think of it as legitimate AJAX.

As a result of using pushState, page loads are noticeably faster. I’ve been measuring most of mine to be coming in between 100 – 150ms. Battery life is also conserved because of the unecessary HTTP request avoidance, and the flash of unstyled text is also eliminated.

Keeping the current page instance alive through pushState is good, but does have its caveats. A lot more testing is needed as pesky edge cases do emerge.

The Red Bull Music Academy Radio and SoundCloud are two of my favourite examples of this in the wild.

Using Sass for legacy IE

I used to use Respond.js as an IE media query polyfill. The trouble is that it has JavaScript dependency and XHRs your style sheets. The performance hit is undesirable. However, using Sass @includes, I’m able to compile a media queried version and non media queried version of the same stylesheet. These are included in IE conditional comments:

<!--[if (gt IE 8) | (IEMobile)]><!-->
<link rel="stylesheet" href="style.css">
<!--<![endif]-->

<!--[if (lt IE 9) & (!IEMobile)]>
<link rel="stylesheet" href="ie.css">
<![endif]-->

Nicolas Gallagher is to credit for popularising this method in his excellent article.

Vanilla JavaScript

jQuery is an absolute godsend, but comes with a price: 32kB and a bundle of code to parse. I found that what I wanted to achieve could all be done in vanilla JavaScript, and by doing this eliminated an unecessary burden on less capable devices.

For any larger scale site or application, I’d probably use a combination of Jeremy Keith’s ‘Conditional CSS’ method and yepnope to load jQuery based on screen width or features:

/* The CSS */
@media all and (min-width: 45em) {
    body:after {
        content: 'widescreen';
        display: none;
    }
}

// The JavaScript
var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
if (size == 'widescreen') {
    yepnope([{
    load: 'jquery.js',
    complete: function () {}
    }]);
}

RequireJS could also be bundled into the file for including modules and increasing speed. Delivering only what is needed, when it is needed.

Caching

It’s important to let your website’s underlying codebase do as little work as possible. Cached pages are like fast food that can be served up in an instant, whereas non cached pages have to be cooked, warmed, packaged and sent the front-end.

Caching on the server side is an essential performance step for any website or application. In the case of this site, I’m using Memcachier: a memcache addon for Heroku. Memory based cache storage is favourable over disk based because it’s faster (think HDD vs. RAM).

Apache are currently developing mod_pagespeed, which performs a lot of useful HTTP caching and asset optimisation at server level. Ilya Grigorik has an excellent write-up on the many things it can do. I anticipate many will adopt this into their responsive toolkit.

Summary

Performance and page ‘responsiveness’ should be part of the process and not an afterthought. The tools are readily available, we just need to choose to use them, and to use them wisely.

I completely agree with Tim Kadlec’s call to action to create a culture of performance:

If you understand just how important performance is to the success of a project, the natural next step is to start creating a culture where high performance is a key consideration.

A tidier approach to using SVG

As the web progresses into a future where screen densities are becoming increasingly uncertain, the need for pixel agnostic graphics is paramount. Blurry graphics really don’t cut the mustard.

I’ve been working with SVG a lot recently, trying to figure out the most robust way to use it. Unfortunately SVG browser support is fairly new, so workarounds are required to provide graceful fallbacks to raster.

My initial proposed solution ‘envelope window SVG’ used visibility: hidden on an image, and hooked in an SVG background onto the parent element. The major flaw to it being that two assets were download where only one was needed. Increased HTTP requests negatively impact performance, which forced me to continue my search. I eventually found SVGfall.

Enter SVGfall

SVGfall is based on the Picturefill library by Scott Jehl. It uses three <div> elements with data-support attributes that are filtered, featured detected and converted into an image. For those browsers that have little or no JavaScript support, a fallback raster image wrapped in <noscript> tags is required at the end.

See a demo

I’ve put together a small demo of it in action.

Hammer for Mac

This is a very useful application for easily creating static HTML sites. Hammer provides handy HTML includes and asset helpers to speed the development process along. No more copy and paste jobs between multiple files. It also mimics the Rails asset pipeline with Sass and CoffeeScript compilers already built in.

It also allows you to publish your builds to Hammer’s own hosting service. Perfect for quickly getting interactive prototypes and visuals out the door and online to show clients.

I can really see this becoming an essential tool in my development workflow.

Routing constraint for High Voltage

High Voltage is a Ruby gem for creating static pages, like ‘about us’, in Rails apps.

When building this site, my post and page routes ran into conflicts with one and other. Whichever route came highest in the routes.rb file took priority, making the one below defunct. In the interest of keeping things clean, the aim was to have all of my routes running from the base of the URI.

This custom constraints method for High Voltage avoids the conflicts by checking for initial matches via request.path, and if not matched, lets them carry on through.

Why I took a one year Facebook hiatus

First, the backstory.

I never had a healthy relationship with Facebook. Not many people do. I felt a constant urge to check it and see if something interesting was happening. It’s addictive, almost like a computer game that demands constant attention but can’t be completed. I found it to be a constant distraction.

This time last year, I stumbled across an alarming statistic on Twitter:

An average Facebook user loses 23 hours a month on Facebook.

Now, I’m not sure how accurate that is, but it works out to roughly 45 minutes of Facebook per day. If you scale that up to a typical lifetime, you’ve lost just over 775 days. That’s 2.7% of an average American’s life span spent on Facebook.

This woke me up. That’s a lot of time to lose — even before texting, email, and other social networks are factored in. It scared me to the extent that I decided to deactivate my Facebook for a while to see what impact it would have. American comedian Andy Borowitz’s quote perfectly sums up my reasons for doing so:

There’s a fine line between social networking and wasting your fucking life.

Perhaps one of my favourite articles talks about this culture of distraction and how we’re becoming increasingly reliant on distractions to plug time gaps where we feel mentally unstimulated.

As Joe Kraus puts it (substitute ‘phone’ with ‘Facebook’):

We threaten the key ingredients behind creativity and insight by filling up all our “gap” time with stimulation. And we inhibit real human connection when we prioritize our phones over our the people right in front of us.

He then goes on…

The effect of all of this is that we’re increasingly distracted. Less and less able to pay attention to anything for what used to be reasonable length of times.

It’s true. Some of us get so sucked into the virtual layer that we can sometimes be oblivious to the things around us. Almost using Facebook as a form of escapism from the task or social situation at hand. It’s a great tool for procrastination.

What strikes me is this: what we perceive as ‘normal’ is often ‘statistically normal’ — i.e. what everyone else does. Facebook has become so pervasive in Western youth culture that not having a profile is considered ‘abnormal’. Sometimes to the extent that people may consider you suspicious. James Holmes didn’t have a Facebook account.

From the outset my intention was to lay off for just a few months, which then extended to just over a year. Deactivating essentially ghosted my profile, whilst keeping my data intact.

Above all else it was a personal experiment to see what effects it would have on my day to day life. Suffice to say the impact has been very noticeable, and for the most part, positive.

The most obvious and noticeable takeaway was being able to stay focussed for longer periods of time and get into a productive flow. Facebook no longer demanded any part of my attention. Without the ability to plug it into gaps of boredom or solitude, I was forced into longer form, insightful thinking. It’s a bit like having a shower, without the shower.

As people weren’t readily available — and I wasn’t readily available to them — I made more effort to keep in touch. Apparently Facebook “helps connect people”, well not the way I see it. Real life conversations help connect people. A friend list, comment or status like on a screen is nothing more than that — it conveys no tone, senses or emotion. Removing the ability to digitally network amongst friends forced me to be more outgoing. Being out of touch and then catching up face to face makes it all the better, too.

Having no Facebook resulted in me plugging myself into Twitter a lot more. Social networking amongst likeminded folk is really powerful. The people I follow — for the most part — aren’t close friends, so I never run risk of getting sucked into reading or sharing anything personal or trivial. It continues to prove itself an invaluable resource for links, articles, opinions, and short burst discussions. The constraint of 140 characters enforces this perfectly.

A definite negative of Facebook abstinence, however, is that being out of the loop is tough — but not impossible. I’d often miss group related messages and invites. Deferring people to email is almost impossible with Facebook taking lead as the preferred means of group communication. That’s one thing it is very good for.

Pros and cons aside, I feel that as a twenty-one year old, Facebook is on balance a necessary evil. Without it, I may be misjudged and misunderstood, and I don’t want either.

Taking a year long break has forced me to get Facebook and other “stop gap” distractions under control and in perspective. Moving forward I hope to have a healthier, more productive relationship with them.