<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Wilson Page - Articles</title>
    <description>Wilson is a front-end engineer in search of a new challenge.</description>
    <link>http://blog.wilsonpage.co.uk</link>
    <atom:link href="http://blog.wilsonpage.co.uk/feed.articles.xml" rel="self" type="application/rss+xml" />
    
      
      <item>
        <title>Onboard Mozilla Turbulence</title>
        <description>This morning I found out that the part of Mozilla that I’ve be working within for the past year had collapsed.
A meeting was scheduled with HR for them to tell me my job is ‘at risk’. In other words I have a few weeks
to find a something new. Here’s my perspective on what happened.

Joining Mozilla

In November 2013 I joined Mozilla to be part of Firefox OS. At the time it was the most ambitious
web project I’d ever seen. I felt closure after shipping a big project at the Financial
Times and jumped on the opportunity at Mozilla.

After countless interviews I got the news that I’d been offered the job. I was ecstatic.
As a young developer (26) I’d just landed my dream job.

I was constantly scared that my cover would be blown, and that someone would find out that I
wasn’t good enough to be here. To circumvent this I gave everything I had. I was working
alongside some of the best web-developers in the world and the inventor
of JavaScript was at the helm … what could be better?

Veering off course

In 2014 following the media storm that hit his promotion, Brendan Eich left Mozilla.
Looking back, it felt like he took some of the magic with him; I think at this point Mozilla began to
drift off course.

The Firefox OS project was no longer a baby. We couldn’t play that
card when people asked: “how many users have you got?”. The product was a
valiant engineering accomplishment, but the user-value proposition was
fuzzy. We still couldn’t answer the question: “why should I buy a Firefox OS phone?”,
which was a clear red flag.

The crash

In late 2015 it was announced that Firefox OS would be ‘passed over to the community’
and that the team would be reborn as ‘Connected Devices’. Our new task was product
innovation in the IoT space. We admitted Firefox OS was too late for the mobile market
but we were told we could be ahead of the curve for IoT.

At this point the team downsized; a lot of inspirational colleagues moved on to new things. I felt deflated and uninspired, but I used the opportunity to expand my knowledge, learning more about lower level systems.

Within my role in Firefox OS I was a professional at the top of my game. I attended
W3C standards meetings, spoke at conferences and on podcasts. Now I found myself
fumbling around in unfamiliar territory. It felt like going back to school.

Repair

Something didn’t feel right. My manager assured me that the team needed
me and kept me onboard. I embraced the situation and took on new roles. I read up
on new product development techniques and made use of my design skills to
communicate product ideas.

Eventually myself and some colleagues in London saw hope in a app concept we called
‘Magnet’. It aimed to enhance real-life experiences by surfacing timely relevant
content.

I buried myself into Project Magnet, trying to ignore the low morale and
uninspiring projects in the rest of the organisation. I developed new engineering
skills in iOS and Android, and learnt a lot about product development.
Ignoring the temptation to build everything upfront and wrapping constraints
around ideas to make them feasible.

Dead weight

Back in the day Firefox OS had to hire fast. As a result we may have pulled people
aboard too hastily. We clearly weren’t all on the same wave length. Mozilla is
comfortable; sometimes people stay for the wrong reasons.

On top of this, we were burnt out. There’s only so many times you can throw
people onto a new project and tell them to give it 110%. We endured failure,
we were being crushed by giant competitors, and that eventually ground
down even the strongest members.

Next

Today Connected Devices is no more. I feel a strange feeling, like learning a close relative
that has been sick for a long time has passed away. There’s both sadness and relief.

I’m a different person than I was the first day I walked into that shiny orange office in London,
giddy with excitement. I’ve travelled to parts of the world I never thought I’d see
and worked alongside some of the best.

I gave Mozilla everything I had. I pushed myself beyond my comfort zone
several times, which forces growth, but takes its toll on relationships.

I’m about to turn thirty. It’s a good time for me to take a step back and decide
what I want to achieve in the next few years.
</description>
        <pubDate>Thu, 02 Feb 2017 23:42:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/mozilla-turbulence/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/mozilla-turbulence/</guid>
      </item>
      
    
      
      <item>
        <title>Fastdom V1</title>
        <description>Just over two years after Fastdom was born, I’m happy to announce a formal V1 release.

Fastdom V1 is 20% smaller (600 bytes minified gzipped) than the previous release. This is largely due to code simplification and removal of some rarely used APIs.

Additions

Fastdom aims to be a tiny unopinionated library, for this reason, in order to meet everyone’s particular needs, we added the ability to .extend() the core library to add additional functionality.

var myFastdom = fastdom.extend({
  measure: function(fn, ctx) {
    // do custom stuff ...

    // then call the parent method
    return this.fastdom.measure(fn, ctx);
  }
});

Fastdom ships with a couple of core-extensions that address some higher-level features people have been asking for.

Changes

Fastdom V1 comes with some (breaking) API name changes.


  fastdom.read() -&amp;gt; fastdom.measure()
  fastdom.write() -&amp;gt; fastdom.mutate()
  fastdom.onError -&amp;gt; fastdom.catch


These name changes were suggested by Paul Irish in an effort to improve clarity over the type of code that should be contained in each block.

Removals

We removed fastdom.defer() as its use-cases were ambiguous and it was rarely used.

Strict mode

It’s very important that all DOM mutations or measurements go through fastdom to ensure good performance; to help you with this we wrote fastdom-strict. When fastdom-strict.js is loaded, it will throw errors when sensitive DOM APIs are called at the wrong time.

This is useful when working with a large team who might not all be aware of fastdom or its benefits. It can also prove useful for catching ‘un-fastdom-ed’ code when migrating an app to fastdom.

&amp;lt;script src=&quot;fastdom.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;fastdom-strict.js&quot;&amp;gt;&amp;lt;/script&amp;gt;

// throws &quot;Can only get .clientWidth during 'measure' phase&quot;
element.clientWidth;

// throws &quot;Can only get .clientWidth during 'measure' phase&quot;
fastdom.mutate(function() { element.clientWidth; });

// does not throw
fastdom.measure(function() { element.clientWidth; });


  fastdom-strict will not throw if nodes are not attached to the document.
  You should use fastdom-strict in development to catch rendering performance issues before they hit production. It is probably not good to use fastdom-strict in production as it wraps APIs.

</description>
        <pubDate>Tue, 05 Jan 2016 17:40:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/fastdom-v1/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/fastdom-v1/</guid>
      </item>
      
    
      
      <item>
        <title>The perfect AMD setup</title>
        <description>I’ve been using AMD modules (RequireJS) for various projects for a while. It has some advantages over ‘CommonJS’ (ie. Browserify) solutions, but has additional complexity around package installation.

One thing I disliked about AMD was having to maintain a large paths config to resolve third-party package sub-dependencies. Here’s an example of one of these:

require.config({
  baseUrl: '/js',

  // 'paths' lets us alias complex
  // paths to something simpler and
  // resolve sub-dependency require paths
  paths: {
    'debug': '../bower_components/debug/index',
    'attach': '../bower_components/attach/index',
    'model': '../bower_components/model/index',
    'view': '../bower_components/view/index',
    'evt': '../bower_components/evt/index',
    'drag': '../bower_components/drag/index',
    'device-orientation': '../bower_components/device-orientation/index',
    'gaia-header': '../bower_components/gaia-header/gaia-header',
    'gaia-icons': '../bower_components/gaia-icons/gaia-icons',
    'gaia-component': '../bower_components/gaia-component'
  }
});

This config means that anywhere in my app code or third-party code I will be able to call require('gaia-component'), and it’ll actually require js/bower_components/gaia-component, under the hood.

As gaia-component is a dependency of the gaia-header module, this path config must be in place, otherwise gaia-header will error.

Installation process

Bower/AMD package installation process is involved and error prone:


  $ bower install cool-package
  Search through source code of cool-package and identify any sub-dependency require()s.
  Amend the require.config paths to map any sub dependency paths to their correct locations.
  Run app, on failure return to step 2.


By contrast the NPM installation process is dreamy:


  $ npm install cool-package
  require('cool-package');


The good news is there’s a better solution for Bower and AMD users which enables:


  $ bower install cool-package
  require('cool-package');


Seamlessly resolving any nested require('some-sub-dependency'). Read on, all will be revealed…

A better solution

I was discussing this problem with James Burke and he kindly wrote a small command-line tool called ‘adapt-pkg-main’ to help. The documentation in the repo is thorough, but I’ll try to outline briefly how it works.

Step One: Package main adapters

Adapt-pkg-main will look for packages in a given packages directory (eg. bower_components/). For each package in the directory it will look for a package description file (eg. bower.json, package.json). Both bower.json and package.json have the convention of a &quot;main&quot; attribute which declares the package’s entry point (eg. cool-package/cool-package.js).

Adapt-pkg-main will use this &quot;main&quot; value to create a new ‘adapter’ module for each package like so:

Main file: bower_components/cool-package/cool-package.js
Created adapter: bower_components/cool-package.js

The cool-package.js adapter is AMD by default, but this ‘adapterText’ can be configured:

define(['./cool-package/cool-package'], function(m) { return m; });

Step Two: require.config

The second part of the trick is to configure RequireJS to assume all unprefixed paths to look in bower_components.

require.config({
  baseUrl: 'bower_components',
  paths: { root: '../' }
});

require(['root/app'])

After this one-time configuration, paths will be resolved as follows:


  require('cool-package') -&amp;gt; bower_components/cool-package.js
  require('some-sub-dependency') -&amp;gt; bower_components/some-sub-dependency.js
  require('./lib/foo') -&amp;gt; CURRENT_MODULE_DIR/lib/foo.js
  require('root/app') -&amp;gt; /app.js


You’ll notice that the unprefixed paths now resolve to the adapter files that adapt-pkg-main created, so the full resolution (via the adapter module) will look like:

require('cool-package') -&amp;gt; bower_components/cool-package.js -&amp;gt; bower_components/cool-package/cool-package.js

Path convention

Once you have this require configuration, it makes sense to use relative style paths whenever you’re requiring a file that doesn’t live in bower_components/, otherwise it’ll have to prefixed with root/. Just write your require() paths exactly as you would in Node.

Automation

It makes sense to plug the adapter creation step into a Bower postinstall hook so we can forget all about it. Create a .bowerrc file at the root of you project (if you don’t already have one) with the following:

{
  &quot;scripts&quot;: {
    &quot;postinstall&quot;: &quot;./node_modules/.bin/adapt-pkg-main bower_components configFileNames=bower.json,package.json&quot;
  }
}

Profit

Drop a comment if you have any questions or improvements :)

bower install sweet-dreams
require('sweet-dreams');
</description>
        <pubDate>Sat, 17 Jan 2015 12:00:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/the-perfect-amd-setup/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/the-perfect-amd-setup/</guid>
      </item>
      
    
      
      <item>
        <title>My journey to Mozilla</title>
        <description>Last November I left my role at the Financial Times and began a new chapter at Mozilla. I’m now over six months into the experience, and only now does it feel like the dust is finally beginning to settle.



Finding Mozilla

Mozilla has quite a presence in London. Ever since I first started mingling in the tech-community, Mozilla was always there in the background. Over the two years of my professional career as a developer I grew friendly with quite a few Mozilla employees and volunteers. In conversations I heard that there was a big recruitment drive for JavaScript developers to work on the new Firefox OS project.

I was in a point in my career where I was looking for my next challenge, and being part of building an operating system purely out of web technologies sounded enormously exciting! I managed to get in contact with a Mozilla recruiter, and this lead to my first interview.

The interview

The process was drawn out. I had five remote interviews with managers and developers from across the Firefox OS project. I’m petrified of technical interviews, I’m rubbish at them. I’m fine having a conversation and discussing approaches, but when it comes to actual coding, I seize up. I feel like I’m being told to defuse a bomb with a gun to my head. Fortunately for me, Mozilla was different.

Interviewers seemed more interested in whether I was the right ‘cultural fit’ for the company. Sure, I got asked plenty of technical questions, but it never felt like an exam or a test. Several interviewers had already seen my GitHub profile and could see that I could code, so perhaps that helped.

Sometimes several weeks went past between interviews and I was sure that I’d screwed up, but after some chasing, I found out this was normal. I eventually got word that I’d made it through to the final ‘on site’. This was in the rather swanky Mozilla Paris HQ, and consisted of three face-to-face interviews with engineers working on Firefox OS.

I was scared, but again I remember the experience being laid-back and friendly. All the questions were practical (not made up puzzles) and I felt comfortably experienced to answer most things confidently. There was the occasional technical question that I didn’t quite understand, for those I was just honest and said “I don’t know”.

It was another few weeks of silence before I heard the news that I had been accepted.



Starting

Mozilla flew me out to San-Francisco for my first three weeks so that I could get to know the company and meet some of my team members. I was to be joining the ‘Media’ team as a front-end engineer working with JavaScript, HTML and CSS. The media team is the biggest of the Firefox OS teams, responsible for: Camera, Gallery, Music, Video, Radio and Ringtones apps.

It was a fantastic start to my new employment, I’d never been to San-Francisco before, and quite frankly didn’t know all that much about Mozilla. I had three weeks to absorb as much as I could before I flew back to UK to go it alone.



Culture

Something was different at Mozilla. I couldn’t quite put my finger on it; it felt like we were a group of excitable children with no parents to tell us ‘no’. There was an overarching sense of humor, but also kindness and responsibility that seemed to find its way into everything. It was in this first week that I realised why ‘culture fit’ was such an important part of the interview process.

Communications

From day one there is an overwhelming stream of information that hits you from all angles, at all hours of the day; people call this ‘The Mozilla Firehose’. It comes in the form email, IRC, video conferencing, wikis, blog posts, Yammer posts, presentations, conferences. You can’t turn it off, and you can’t digest it all.

Everyone seems to have there own way of managing the ‘firehose’. My strategy was to block out as much as I could, stay focused, and then gradually over time, take on more and more when I felt comfortable.

Timezones

I was/am the only member of my team working out of Europe, all my other team members were eight hours behind me on Pacific time. My manager was initially concerned about this, but I assured her it wouldn’t be a problem. This remained in the back of my mind for the first few months, and lead to me working ludicrously late, just to stay in sync with the US.

This proved unsustainable. The pressure of a new job is bad enough, but lack of sleep and long hours made things worse. I had only myself to blame, but I still felt I had something to prove. I was on a mission to re-assure my manager and colleagues that they had made the right decision hiring me.

I was approaching burnout and needed to do something about it. My colleague Anthony, was fantastic; he recognised and stepped in to advise me on how best to manage my time to avoid this happening again. But in all honesty, I only truly relaxed once I received enough indications from my manager that she was happy with my progress.

Travel

At Mozilla travel is trivial. Employees are constantly flying between offices for work weeks, conferences and meetings. On my return from the Christmas break I opened my email to find that I would be flying to Taipei in just over a week to meet with a company that would partner with us on the new camera app.

This was then shortly followed-up with a another trip to Korea for an intense camera work week. It was really exciting to be able to visit countries that I’d never seen before as part of my work.

Although, like I’ve heard from many others, travel isn’t always as glamorous as it appears. I personally found all three trips very lonely at times, exotic places aren’t half as much fun when you don’t have anyone to share them with. Asia especially, is so different it’s easy to feel alien. I’m not saying I regret any of the travel, it’s just something that suprised me at times.



Working remotely

Mozilla employees are remote by default. If you happen to live near an office you are welcome to a desk. I have a desk in the Mozilla London office, but the rest of the Media team are scattered around the world.

Like most, I have a combination of working from home and from the office. Working from home avoids the commute, giving me a couple of extra hours in my day, but can get claustrophobic; a few days a week in the office helps to balance this.

The most exciting thing is that my job now doesn’t tie my to a location. I could pack my bags and go live anywhere in the world and it wouldn’t change my working life. As it happens I kinda like London, but the feeling of choice and freedom is special.



What I’ve learnt

The journey so far has been fantastic; everyday I’m meeting new people and learning new things. It’s scary to dive into something new, but it’s very rare that you’ll regret it. I saw this opportunity, and chased it with everything I had.

I constantly fear I’m punching above my weight; not good enough to work here. Even if that is true, ability is contagious. Surround yourself with talented people and learn from the best!
</description>
        <pubDate>Sun, 03 Aug 2014 12:28:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/my-journey-to-mozilla/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/my-journey-to-mozilla/</guid>
      </item>
      
    
      
      <item>
        <title>The component approach</title>
        <description>One of the most important things I’ve learnt in my time as a front-end developer is the value of ‘components’. We hear the term being tossed around all to often in the community, but to many of us components are still a foreign concept.

In this article I will aim to clarify:


  What we really mean by ‘components’.
  How we can make our own components.
  What the advantages to this approach are.


What is a component?


  “a part that combines with other parts to form something bigger”
 - Cambridge Dictionary


When I talk about a component in the context of development, I’m referring to a distinguishable part of user interface that when combined with other parts, forms a final application. A UI component comprises of markup (HTML), styling (CSS) and, when needed, interactions (JS).

Encapsulation

A component is usual self contained. This means that even in isolation the part should fulfill its responsibilities.

Machinery is a great metaphor for this. A car a is full of components, many of these are made and tested in isolation by manufacturers across the world. Each component has a strict specification, so that when they are brought together at the assembly stage they can smoothly interact together, and form final product. Let’s look at one part in particular: the starter motor.

The starter motor



The starter motor has one job: when a 12v current is connected at one end (expected input), the cog at the other end must spin (expected output). The user (the person assembling the car) need not be aware of the how the part does it’s job, but just how to provide the expected input and make use of the expected output.

The &amp;lt;video&amp;gt; element

Let’s jump to an example a little closer to home: the &amp;lt;video&amp;gt; element. This is a prime example of a component. It has an expected input: the src attribute, and and expected output: a playable video element. What goes on under the hood, is not really a concern to us as ‘the user’ of the component.



The &amp;lt;video&amp;gt; element is a little more complicated to  work with than the starter motor. Is has a larger interface and has many different states. Fortunately the component gives us a simple public interface to control it,


  video.play()
  video.pause()
  video.load()
  video.canPlayType(format)


And can tell us when its state changes via events that we can listen to using the standard .addEventListener() API,


  'canplaythrough'
  'ended'
  'error'
  'playing'
  'progress'
  'waiting'
  'loadedmetadata'


These tools give us as ‘users’, full control over the &amp;lt;video&amp;gt; element without having to know any of it’s internal makeup. To us it’s a black box, and this is a very good thing!

Definition

There are infinite ways to define components. You don’t even need a framework or library to being working with components.

var MyComponent = function() {
  this.el = document.createElement('div');
};

MyCompoent.prototype.render = function() {
  this.el.innerHTML = 'hello world';
};

// Create one
var component = new MyComponent();

// Render it
component.render();

// Put it in the DOM
document.body.appendChild(component.el);

Although simplistic, this vanilla approach has scope to get messy, and in large teams, believe me, it will!

At the Financial Times we wrote a library called FruitMachine to do the job of defining and assembling our view components. FruitMachine established team conventions and guaranteed interoperability of components.

The same component created using FruitMachine would look like,

var MyComponent = fruitmachine.define({
  name: 'my-component',
  template: function() {
    return 'hello world';
  }
});

// Create one
var component = new MyComponent();

// Render it
component.render();

// Put it in the DOM
component.appendTo(document.body);

Why build our own?

There are many pre-existing libraries we could have chosen to do the job of managing our layouts, but we had some specific requirements:


  New components need to easily work alongside old legacy code.
  Layouts need to be able to be rendered as strings on the server-side.
  Should have the ability to define layouts as an arbitrary collection of components.
  No large dependencies (eg. jQuery).


Retro-fitability

Large applications tend to live for a long time. Code bases grow, and as a result complete application re-writes become unfeasibly expensive. It is beneficial with these kind of applications to be able to introduce new architectural changes incrementally, so this was a big requirement for our component library.

To achieve this, a view library has to be relatively un-opinionated about the rest of my application, so that it can be used alongside old code.

Library weight was also a concern. It is unlikely that the rest of your team will be happy with you experimenting with a new approach if it is costly to do so. Start small. Plant experimental seeds of change; if an experiment is a success, it will organically spread across the application.

FruitMachine started just like this. At first rendering only a tiny part of our application. Today, every view is rendered using it.

Declarative layouts

The Financial Times web-app consists of many different pages. Each one of these pages are similar, but essentially different. The secret to managing all these pages is down to components.

We are able to have a single ‘page controller’ that can render all these different pages. The thing that differs is what we call the ‘layout definition’. This is a JSON like representation of our view.

{
  &quot;module&quot;: &quot;layout-a&quot;,
  &quot;children&quot;: {
    &quot;slot1&quot;: {
      &quot;module&quot;: &quot;header&quot;
      &quot;model&quot;: { &quot;title&quot;: &quot;My Web App&quot; }
    },
    &quot;slot2&quot;: {
      &quot;module&quot;: &quot;big-story&quot;
      &quot;model&quot;: {
        &quot;title&quot;: &quot;Story title&quot;,
        &quot;body&quot;: &quot;Story body...&quot;
      }
    },
    &quot;slot3&quot;: {
      &quot;module&quot;: &quot;small-stories&quot;
      &quot;model&quot;: [
        {
          &quot;title&quot;: &quot;Story title&quot;,
          &quot;body&quot;: &quot;Story body...&quot;
        },
        {
          &quot;title&quot;: &quot;Story title&quot;,
          &quot;body&quot;: &quot;Story body...&quot;
        },
        {
          &quot;title&quot;: &quot;Story title&quot;,
          &quot;body&quot;: &quot;Story body...&quot;
        }
      ]
    }
  }
}

If we feed this definition to FruitMachine, it will spit out a fully formed view ready to drop into the DOM.

var layout = fruitmachine(layoutJSON);

layout
  .render()
  .appendTo(document.body);

Server-side rendering

There can be advantages to rendering on the server-side,


  Site/App crawlability
  Fast ‘time to content’


We wanted these options available to us in the future, so this was a requirement for FruitMachine. The app also had to work offline, meaning that all views needed to be able to render on the client-side when a server wasn’t accessible. This had a big impact on how the library could operate.

Nested view structures needed to be rendered as HTML strings when the DOM isn’t present. These strings would be sent to the client in the page response body and ‘inflated’ to become fully functional components, just as if they has been rendered on the client.

The are other advantages to a component library not requiring a document.


  Layouts can be rendered inside a WebWorker
  Side-step browser DOM API inconsistencies


Summary


  Choose a component solution that best matches your requirements.
  We wrote FruitMachine as a bespoke component solution that:



  Could integrate with existing code
  Was as light as possible
  Had the option to render server-side
  Could interpret declarative layout definitions


Styling components

Getting all your components onto the page, rendered with the correct content is just half the job. We’ve still got to style them.

CSS is a hard beast to tame, but ‘componentising’ your CSS just like your JS can make life a lot easier! When working with complex apps I have always used the SASS pre-processor. This is of course not a requirement when working with components, I would just recommend it.

For each component we create a .scss. This file will live in a flat directory alongside all our other components. We don’t attempt to group or categorize anything, all components are created equal!



Next we need to get on and start styling our component, our main priorities here are supporting transportability and preventing leakage. Currently the only way we can achieve this is by pure discipline. Further down the road, we should be able to depend on new techniques of style encapsulation via ‘Shadow DOM’ and ‘Scoped-stylesheets’, but for now, we’re kind of alone.

Consider the following component:

&amp;lt;article&amp;gt;
  &amp;lt;h1&amp;gt;Headline&amp;lt;/h1&amp;gt;
  &amp;lt;p&amp;gt;Body content&amp;lt;/p&amp;gt;
&amp;lt;/article&amp;gt;

One option for styling this would be:

article {
  padding: 1rem;
}

h1 {
  font-size: 3rem;
  margin-bottom: 1rem;
}

p {
  margin-bottom: 1rem;
}

This is a style leak nightmare! Those three rules will affect every other &amp;lt;artice&amp;gt;, &amp;lt;h1&amp;gt; and &amp;lt;p&amp;gt; in your application. Think of those rules as window globals in JavaScript. We have learnt to use closures to limit the scope of our variables in JavaScript; in CSS there is no concept of scope, so we need to fake it.

Let’s add some classes to these elements to differentiate them from the those of the same tagName.

&amp;lt;article class=&quot;my-article&quot;&amp;gt;
  &amp;lt;h1 class=&quot;headline&quot;&amp;gt;Headline&amp;lt;/h1&amp;gt;
  &amp;lt;p class=&quot;body&quot;&amp;gt;Body content&amp;lt;/p&amp;gt;
&amp;lt;/article&amp;gt;

And style them:

.my-article {
  padding: 1rem;
}

.my-article .title {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.my-article .body {
  margin-bottom: 1rem;
}

It’s nothing complex, but disciplined convention has given us the illusion of ‘scope’. My styles will no longer leak and impact components written by my team. But what this doesn’t protect us against is poorly written styles by other team members or third-parties.

Suppose another developer has carelessly written:

.title {
  color: red;
}

This case of common of class names will result in my component turning red. We must protect ourselves from this carelessness!

&amp;lt;article class=&quot;my-article&quot;&amp;gt;
  &amp;lt;h1 class=&quot;my-article_headline&quot;&amp;gt;Headline&amp;lt;/h1&amp;gt;
  &amp;lt;p class=&quot;my-article_body&quot;&amp;gt;Body content&amp;lt;/p&amp;gt;
&amp;lt;/article&amp;gt;

.my-article {
  padding: 1rem;
}

.my-article_title {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.my-article_body {
  margin-bottom: 1rem;
}

There is now a very high probability our classes are unique, and we have prevented both leakage, and being leaked upon.

Using prefixed classes negates the need for parent selectors, this means that the elements within our component are portable. We can change our markup structure are not have to worry about updating our CSS, this speeds up development.

Summary


  Use the component name as the class of the component’s root element.
  Prefix all sub-elements like component-name_* to prevent (and protect from) leakage.
  Avoid polluting the global scope with generic class and tag selectors.


Plugins

Scope

Understanding the scope a component should have is crucial to maintaining a manageable code-base. I like to think of each UI component I write as a mini-app, or document.

By adopting this approach we write components that are completely decoupled from our application. Theoretically I could pick up a component written in one application and drop it into another. I’ve heard arguments that this is not a realistic use case, and perhaps that is true; but the subtle side affects that come with this approach are invaluable.

var MyComponent = fruitmachine.define({
  name: 'my-component',
  printName: function() {
    var container = document.querySelector('.container');
    container.innerHTML = 'my name is ' + this.name;
  }
});

/**
 * Usage
 */

var component = new MyComponent();
component.printName();

The above component is badly behaved. It’s making assumptions about its context, this smells like a tightly coupled component and tightly coupled components don’t smell nice.

MyComponent will only work correctly if .container is in the DOM when .printName() is called. If I’ve been assigned some work related to MyComponent, I, as a developer, must also understand other things about the application before I can start working on it.

Injecting dependencies

We can work around this problem by feeding our component the things it needs when we create it.

var MyComponent = fruitmachine.define({
  name: 'my-component',
  initialize: function(options) {
    this.container = options.container;
  },
  printName: function() {
    this.container.innerHTML = 'my name is ' + this.name;
  }
});

/**
 * Usage
 */

var container = document.querySelector('.container');
var component = new MyComponent({ container: container });

component.printName();

Our component is now making no assumptions about our application. Our application code it doing the job of linking .container with component. This is good, our application code shouldn’t be reusable, it’s the intelligent mortar between dumb bricks.

Contribution

Joining a large project is scary; there are a lot of unknowns. Making changes to a codebase you’re not familiar with can often feel like defusing a bomb.

An application comprised of many tightly scoped components can reduce the barrier to contribution. Devlopers can familiarise themselves with a small chunk of the application, and quickly feel comfortable making changes.

Tightly scoped components can dramatically reduce the barrier to entry for new contributors. Large tangled code-bases can become a minefield for new developers on the team. New developers can dive straight in and start making changes to components

Summary


  Treat each component as a ‘mini-app’.
  Write ignorant components that don’t depend on a their context.
  If a component needs to know something outside of its scope, pass/inject it in on instantiation, don’t make it fetch it itself.


Communication

For a component to integrate into an application it requires two way communication. The component should expose a public API to allow the parent application to use it, and should emit events to notify the application when things have happened.

This approach has been proven to work by native components such as the &amp;lt;video&amp;gt; element. But it’s important to play by the rules to stop things getting out of hand.

Components shouldn’t control your app

I’ve seen developers breaking component scope all too often. It’s tempting to call application API form directly within your component, but by doing this your greatly increasing the risk of circular dependencies. You application requires the component, your component requires your application. This is the point where code starts to get messy.

Application -&amp;gt; MyComponent -&amp;gt; Application

var galleryController = require('gallery-controller');

var ImageComponent = function(src) {
  this.el = document.createElement('image');
  this.el.src = src;
  this.el.addEventListener('click', function() {
    galleryController.showGallery();
  });
};

Events allow us to keep the dependency chain linear, and pass communication back up the chain.

Application &amp;lt;-&amp;gt; MyComponent

Events shouldn’t be used as API

Events are powerful, but they can be used in the wrong way. One application I worked on became an event based nightmare after developers started using event emitters for the first time.

Instead of modules having an explicit API, they responded to events. Calling an event had a chain reaction of affects across the application, that quickly span out of our control. I learnt some very important lessons from that project:


  Call API to cause something to happen
  Use events to signal when something has happened
  Fire from where the event happened (target)


Example

I’ll try to illustrate my point with a simple example of two components: MyButton and MyOverlay. I want like to show the overlay when the button is clicked.

var MyButton = fruitmachine.define({
  name: 'my-button',
  tag: 'button',
  setup: function() {
    var self = this;
    this.el.addEventListener('click', function() {
      self.fire('click');
    });
  }
});

var MyOverlay = fruitmachine.define({
  name: 'my-overlay',
  show: function() {
    this.el.classList.add('visible');
  }
});

var overlay = new MyOverlay();
var button = new MyButton();

overlay
  .render()
  .appendTo(document.body)

button
  .render()
  .appendTo(document.body)
  .on('click', overlay.show);

Bubbling

I think one of the coolest things about the DOM is event propagation. As FruitMachine evolved we saw the opportunity to implement a similar concept to further decouple our application controllers from view components.

Our application layouts were a nest hierarchy of components. The specific components in the layout depended on the layout definition. This meant that our controller could not always be sure or which components it was controlling, and we often ended up with code like.

var button = layout.module('my-button');
if (button) {
  button.on('click', overlay.show);
}

This started to become very messy. We needed a simpler way to bind to events from unknown components in the view.

We came up with the solution of event bubbling and delegate event listeners, a familiar pattern, except this time applied to components.

It was a simple change: when an event fires on a component, we would also fire it on the parent component; effectively bubbling the event all the way to the layout root. This greatly simplified our application code.

layout.on('click', 'my-button', overlay.show);

If my-button doesn’t exist as a child component of layout, it doesn’t matter. Everything will continue to work as expected.

Summary


  Events are critical to a decoupled component based architecture.
  Components emit events when they need to tell the application something has happened inside their world.
  Use API to cause change.
  Use events to respond to changes.


Performant components

We’ve established that a well written component should be tightly scoped and ignorant. This keeps code clean and decoupled. But our components have permission to do anything in their domain, even DOM manipulation. But can’t badly managed DOM manipulation get expensive? Yes, yes it can.

Layout thrashing

Layout thrashing is the act of repeatedly writing to, and then reading from, the DOM. It’s expensive.

componentA.innerHTML = 'I am component A'; // Write
componentA.clientHeight; // Read (reflow)

// ...

componentB.innerHTML = 'I am component B'; // Write
componentB.clientHeight; // Read (reflow)

// ...

componentC.innerHTML = 'I am component C'; // Write
componentC.clientHeight; // Read (reflow)

Your application should ideally never ‘layout thrash’, but this is easier said than done, especially now we have loads of black-box components doing whatever they like with our temperamental DOM. We need a way to orchestrate component’s DOM interactions if want to keep our application fast. I wrote FastDOM to solve this problem.

FastDOM

FastDOM wraps your DOM read/write work, and runs it on the next animation frame in two batches: reads, then writes. This avoids layout thrashing as the DOM is only being reflowed a maximum of once per frame.

fastdom.write(function() {
  componentA.innerHTML = 'I am component A'; // Write
  fastdom.read(function() {
    componentA.clientHeight; // Read
  });
});

// ...

fastdom.write(function() {
  componentB.innerHTML = 'I am component B'; // Write
  fastdom.read(function() {
    componentB.clientHeight; // Read
  });
});

// ...

fastdom.write(function() {
  componentC.innerHTML = 'I am component C'; // Write
  fastdom.read(function() {
    componentC.clientHeight; // Read
  });
});

What used to cause three document reflows, now only causes one.

Layout Boundaries

Another interesting discovery I made in my quest for performance was ‘layout boundaries’. Whenever the DOM changes, the browser must perform ‘layout’ to calculate the size and position of each element on the page.

The browser starts at the point in the DOM that was changed, walking its way up the DOM tree laying out each node that it encounters. It will keep walking until it hits a layout boundary, more often than not, this is the the document root (&amp;lt;html&amp;gt;), meaning the whole document is laid out again.

When an element has a specific set of style properties, it classifies as a layout boundary. Introducing layout boundaries limits the scope of layout, making the whole layout operation faster.

In order to act as a layout boundary, an element must:


  Not be display inline or inline-block
  Not have a percentage height value.
  Not have an implicit or auto height value.
  Not have an implicit or auto width value.
  Have an explicit overflow value (scroll, auto or hidden).
  Not be a descendant of a &amp;lt;table&amp;gt; element.


In other words: if you set a px or % width, px height and set overflow to hidden; a &amp;lt;div&amp;gt; becomes a layout boundary.

In the Financial Times app we used this technique to make the root element of each of our components a layout boundary. Events that occurred after the initial page render, such as lazy image loads, or animations would only ever cause the single component to re-layout, not the entire document.

After this change, we saw layout performance improvements of up to 3x!

[Insert devtools screenshot]

Summary


  Use a tool like FastDOM to harmonize thrashing components.
  Experiment with layout boundaries to improve post-render layout performance.


Responsive components

Modern web applications need to be able to adapt their layout to fit the device in use. A lot has been written about how applications can make use of media-queries to change the appearance of elements on the page, but sometimes this isn’t enough.

When our applications are made up of components, many of theses components are going to need to change in appearance, and some of these components are going to need to change their behaviours and interactions.

Transforming components

We first faced this challenge when designers passed us visuals for a page that, in landscape, had a scrolling story component, but in portrait, a tabbed component with the same content.

We didn’t want to have to use two separate components for this job. We wanted a single semantic piece of HTML, that simply looked and behaved differently at declared breakpoints.

Defining breakpoints

For this job we wrote a re-usable plugin for our FruitMachine library. The plugin allowed you to declare more granular setup and teardown logic on a per breakpoint basic.

var MyComponent = fruitmachine.define({
  name: 'my-component',

  breakpoints: {
    'column': {
      setup: function() {
        // Add scrollers
      },
      teardown: function() {
        // Remove scrollers
      }
    },
    'row': {
      setup: function() {
        // Add tab click logic
      },
      teardown: function() {
        // Remove tab click logic
      }
    }
  }
});

Listening for breakpoints

We then needed a way to know when a component entered and left one of the defined breakpoints. Out first solution was based on a solution I first read about on Jeremy Keith’s blog. It involved changing the content value of a hidden pseudo element using media-queries.

@media(orientation: landscape) {
  .my-component:after {
    content: 'column'
  }
}

@media(orientation: portrait) {
  .my-component:after {
    content: 'row'
  }
}

Then checking the value of this content property in JavaScript, whenever the window was resized.

window.addEventListener('resize', function() {
  window.getComputedStyle(myComponent.el, ':after').content; //=&amp;gt; 'column'|'row'
});

In the full implementation we would store the value of the last state so that we could detect when the component changed state. The callback was also ‘debounced’ so that it didn’t run too frequently.

This implementation allowed us to couple JavaScript logic to breakpoints defined in our CSS. It was relatively simple and it worked, but later proved to be one of the biggest bottlenecks in our layout performance when we started to roll the app out across lower end devices.

It turned out that window.getComputedStyle() causes document layout, and is pretty expensive, especially when run several times a second per component! We needed a better solution.

window.matchMedia

I knew what I had created was pretty horrific, and I needed to come up with a better solution quickly, before the rest of my team found out what I had done. Luckily I stumbled across a less well known feature of window.matchMedia.

I had known for a while that matchMedia was able to tell you whether the document currently matched a given media-query. What I didn’t know was that you could attach listeners that would tell you when the given media-query became matched or unmatched. This was exactly what I needed, it was time to shift.

I re-wrote the FruitMachine plugin to interpret two properties of the component definition: media and states.

var MyComponent = fruitmachine.define({
  name: 'my-component',

  media: {
    'orientation: landscape': 'column',
    'orientation: portrait': 'row'
  },

  states: {
    'column': {
      setup: function() {
        // Add scrollers
      },
      teardown: function() {
        // Remove scrollers
      }
    },
    'row': {
      setup: function() {
        // Add tab click logic
      },
      teardown: function() {
        // Remove tab click logic
      }
    }
  }
});

The media property mapped media-queries to states. The plugin would also add the currently matching state as a class to the component. This allowed us to keep all our media-queries in JavaScript, and not have to duplicate them in the CSS.

.my-component.column {
  /* 'column' styling */
}

.my-component.row {
  /* 'row' styling */
}

This proved to be a lot more efficient. We no longer had to use window.getComputedStyle and we no longer needed our window ‘resize’ listeners.

Overriding defaults

The has been heated debates over the deficiencies of @media at the component level, and strong cases have been made for the @element level media-queries. But unfortunately, they don’t exist yet, and we have to build apps now!

As we reused components in different parts of the app, the default media-queries weren’t always appropriate. We needed a way to define what these media-queries should be on a per-instance basis. Fortunately, because our media-queries were now in JavaScript, this wasn’t too tricky to build into our plugin.

Let’s say in an different layout we wanted our article component to be in ‘row’ form in landscape and ‘column’ form in portrait.

var component = new MyComponent({
  media: {
    'orientation: landscape': 'row',
    'orientation: portrait': 'column'
  }
});

This added control enabled us to solve further unforeseen problems in the app, and allowed us to re-use components in places where otherwise we would have had to write from scratch.

Conclusion

Moving towards a component approach has completely changed the way I think about front-end development. Building applications from small building blocks is manageable and it scales. Whatever your framework of choice, the same lessons usually apply.


  Keep components tightly scoped to promote reuse and reduce tangled code-bases
  Make components configurable to maximise their usage
  Expose a public interface so components can be controlled
  Use events to react to changes inside components
  Timeline your apps to keep an eye out costly DOM work
  Use smart CSS selectors for rock solid styling
  Look to existing web-components (like &amp;lt;video&amp;gt;) for inspiration
  window.matchMedia can help with complex ‘behavioural’ breakpoints


If we’re going to get better and better as an industry we should look at at the lessons learnt in other engineering disciplines. Manufacturing an entire car from scratch is no longer competitive, parts are manufactured and sourced from all over the world, then assembled in one place.

Imagine a web of trusted, shareable components at our fingertips. More people, building higher quality applications, with ease. If we embrace this change, if build this platform, we can make the web win.
</description>
        <pubDate>Fri, 14 Mar 2014 17:10:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/the-component-approach/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/the-component-approach/</guid>
      </item>
      
    
      
      <item>
        <title>Installing Firefox OS on Nexus 4</title>
        <description>I just managed to flash my Nexus 4 device with Firefox OS, here are the steps I went through to do it.

1. Install ADB

ADB is the tool we use to communicate with our Firefox OS device from our machine. Before you can flash any devices with new versions of Firefox OS, you need to have this tool installed.

Download it with the Android SDK, and make sure both adb and fastboot executables are available on your command-line.

2. Turn Android into Firefox OS

2.1 Download the following package

2.2 Unzip and cd ./mako

2.3 Power off device.

2.4 Power on device holding Volume Down + Power.

2.5 Select reboot bootloader.

2.6 Run ./flash.sh.

Your device should then reboot as a Firefox OS device. Next we want to get the freshest version of Firefox OS onto your Nexus 4. This takes a little more work, but will mean that you will be able to develop at the bleeding edge.

3. Create a case-insensitive ‘mountable disk image’

I know, sounds like gibberish right? But B2G is built on Android, which requires a case-insensitive file system for particular builds. Most B2G build don’t require this, but the Nexus 4 does.

MacOSX does not have a case-insensitive file system by default, but allows you to create virtual drives that do. The following instructions were copied from here.

3.1 Create a new drive

hdiutil create -volname 'firefoxos' -type SPARSE -fs 'Case-sensitive Journaled HFS+' -size 40g ~/firefoxos.sparseimage

3.2 Mount the drive

open ~/firefoxos.sparseimage

3.3 cd into it

cd /Volumes/firefoxos/

4. Clone the B2G onto your mounted drive

git clone https://github.com/mozilla-b2g/B2G.git
cd B2G

5. ‘Config’ B2G for this device

./config.sh nexus-4

Warning: this could take a while…

6. ‘Build’ B2G

./build.sh

Warning: this could take a while…

If at any point throughout this process the build scripts error, it is most likely that you are missing a dependency. Check what the error message is complaining about, and go use HomeBrew to install it.

7. Flash new Gaia and Gecko

./flash.sh gecko
./flash.sh gaia

You now have a completely fresh, up-to-date version of Firefox OS on your Nexus device.


  Props to Ryan Watson for improvements.

</description>
        <pubDate>Wed, 12 Feb 2014 21:50:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/installing-firefoxos-nexus4/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/installing-firefoxos-nexus4/</guid>
      </item>
      
    
      
      <item>
        <title>Make your Documents folder your Dropbox</title>
        <description>I recently purchased a premium Dropbox account to make working across multiple machines a little easier. I didn’t want to have to think about what and when to move stuff into my Dropbox, I just wanted my Documents folder to be my Dropbox.

1. Move your Documents into Dropbox

First you need to copy any existing contents of your Documents directory into a new directory inside your Dropbox folder named ‘Documents’.



2. Delete your Documents directory

Now your Documents directory empty is empty we need to delete it. OSX won’t let you do this from finder so we have to go open terminal.

$ sudo rm -rf ~/Documents

3. Link your Dropbox Documents

Now we create a ‘symlink’ (or ‘alias’) of the new ~/Dropbox/Documents directory back to the original Documents locations.

$ ln -s ~/Dropbox/Documents ~/Documents



That’s all there is to it.
</description>
        <pubDate>Sat, 16 Nov 2013 17:25:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/make-your-documents-folder-your-dropbox/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/make-your-documents-folder-your-dropbox/</guid>
      </item>
      
    
      
      <item>
        <title>CSS sibling selectors</title>
        <description>The are two selectors in CSS which are able to target siblings, + and ~. There are few use cases for these selectors, but in the past I have been very thankful for their existence.

Adjacent sibling (+)

The adjacent sibling selector will match the next element in the DOM.

&amp;lt;div class=&quot;a&quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div class=&quot;b&quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div class=&quot;c&quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div class=&quot;d&quot;&amp;gt;&amp;lt;/div&amp;gt;

Let’s colour the next div after .a green.

.a + div {
  background: green;
}

Adjacent sibling demo

General sibling (~)

The general sibling selector is similar, but will style all the siblings after a particular element.

&amp;lt;div class=&quot;a&quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div class=&quot;b&quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div class=&quot;c&quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;div class=&quot;d&quot;&amp;gt;&amp;lt;/div&amp;gt;

Let’s colour all the divs after .a green.

.b ~ div {
  background: green;
}

General sibling demo

Use case: Markup dependent styling

These selectors particularly useful when working with dynamic markup. If you are working with a data feed, for example news stories, it is unpredictable how much data each story will have. Some stories might have images, some might not. We can use sibling selectors to style stories differently depending on the markup that has been rendered. Consider the following the markup:

&amp;lt;li&amp;gt;
  &amp;lt;h2&amp;gt;Story 1&amp;lt;/h2&amp;gt;
  &amp;lt;p&amp;gt;Summary paragraph....&amp;lt;/p&amp;gt;
&amp;lt;/li&amp;gt;
&amp;lt;li&amp;gt;
  &amp;lt;h2&amp;gt;Story 2&amp;lt;/h2&amp;gt;
  &amp;lt;p&amp;gt;Summary paragraph...&amp;lt;/p&amp;gt;
&amp;lt;/li&amp;gt;
&amp;lt;li&amp;gt;
  &amp;lt;h2&amp;gt;Story 3&amp;lt;/h2&amp;gt;
  &amp;lt;img src=&quot;http://example.com/image.jpg&quot; /&amp;gt;
  &amp;lt;p&amp;gt;Summary paragraph...&amp;lt;/p&amp;gt;
&amp;lt;/li&amp;gt;

We can use sibling selectors to hide the summary paragraph when a story has an image.

img ~ p {
  display: none;
}

We could then choose to show the paragraph using media queries when the screen is big enough. This is a responsive technique I have found useful in some complex layouts I have worked on in the past.

Markup demo

Use case: Styling by checkbox state

We can use sibling selectors to style things depending on checkbox/radio-button state. This is often how people create some of those crazy interactive experiments without using any JavaScript.

input:checked ~ div {
  background: green;
}

Checkbox demo
</description>
        <pubDate>Thu, 31 Oct 2013 17:25:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/css-sibling-selectors/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/css-sibling-selectors/</guid>
      </item>
      
    
      
      <item>
        <title>Commenting CSS</title>
        <description>Commenting CSS is critical if you are to inform fellow team members (or even just your future self) why you have written code as you have. Code is re-written all the time, and if clever solutions/hacks are not documented, they can easily be left out; this all to often how style regressions get introduced. Clean, consistent formatting also suggests a level of code quality that contributors will feel inclined to match.

Header

I use a brief header comment to title the file and add a sentence or two about what the file does. This is not only useful for newcomers, but can help identifying source files when looking at built CSS in dev tools.

/**
 * Footer
 *
 * The main application footer
 * found on all pages.
 */

.footer {}

Notes

If it is not 100% clear why a particular rule is in place, comment it. I have borrowed a ‘footnote’ technique I saw Nicolas Gallagher using in normalize.css. It’s awesome because your comments can be as long as you want without them getting in the way of your code.

/**
 * 1. Required for correct positioning
 *    of absolutely positioned descendants.
 * 2. Clears floats
 */

.footer {
  position: relative; /* 1 */
  overflow: hidden; /* 2 */
}

Dividers

Files will consist of different parts. I use a standard divider comment to clearly split these parts out, this makes finding things quicker.

.footer {}

/** Links
 ---------------------------------------------------------*/

.footer_links {}

/** Copyright
 ---------------------------------------------------------*/

.footer_copyright {}

Make sure that what ever you choose to be your divider is a ‘snippet’ in all dev’s code editors. To insert a divider in my editor (Sublime Text) all I have to do is type 'div' + tab, and it prints it for me. Find out how to setup snippets in Sublime Text 2.

State overrides

I like to clearly indicate when I’m overriding default styling by using an @state comment block. When I see an @state comment, I know the styling that follows it will only take affect if certain criteria are met. A ‘state’ could be screen size, orientation, body classes, pseudo classes, state classes, attributes…almost anything!

.button {
  background: blue;

  /**
   * @hover
   */

  &amp;amp;:hover {
    background: red;
  }

  /**
   * @active
   */

  &amp;amp;:active {
    background: green;
  }

  /**
   * @large screen
   */

  @media (min-width: 700px) {
    font-size: 2em;
  }

  /**
   * @hide-all-buttons
   */

  .hide-all-buttons &amp;amp; {
    display: none;
  }
}

Single line breaks

For consistency I chose to one empty line break between all blocks. I first saw TJ Holoway Chuck using this style in JavaScript and thought it looked beautifully clean. I love the consistent ‘rhythm’ it seems to bring when reading. I have been replicating it in my JS and CSS code ever since.

/**
 * Module
 *
 * A description of Module.
 */

.module {}

/** Foo
 ---------------------------------------------------------*/

/**
 * 1. This needs a comment
 */

.module_foo {
  position: relative; /* 1 */
}

/** Bar
 ---------------------------------------------------------*/

.module_bar {
  position: relative;

  /**
   * @hover
   *
   * Say why the background
   * turns red when hovered
   * if need be.
   */

  &amp;amp;:hover {
    background: red;
  }
}

Comment line length

I try to keep the line length of comments under 40 characters. For me it seems to make comments a little more digestible.

/**
 * Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore
 * magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis
 * nisl ut aliquip ex ea commodo consequat.
 */

.hard-to-read {}

/**
 * Lorem ipsum dolor sit amet,
 * consectetuer adipiscing elit,
 * sed diam nonummy nibh euismod
 * tincidunt ut laoreet dolore
 * magna aliquam erat volutpat.
 *
 * Ut wisi enim ad minim veniam,
 * quis nostrud exerci tation
 * ullamcorper suscipit lobortis
 * nisl ut aliquip ex ea commodo
 * consequat.
 */

.easy-to-read {}

Conclusion

Commenting is a small thing, but can have big impact, especially when working on large teams. It doesn’t only inform and guide fellow developers, preventing silly regressions; it underpins a code quality standard.

If code is messy and undocumented, it grants permission for other team members to do the same. Quickly your new shiny code base begins to turn into that all too familiar tangled hacky mess. In society this is known as the ‘broken windows theory’, I would argue this theory applies to code too.
</description>
        <pubDate>Wed, 30 Oct 2013 00:17:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/commenting-css/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/commenting-css/</guid>
      </item>
      
    
      
      <item>
        <title>Styling states in CSS</title>
        <description>Creating dynamic, responsive applications means parts of our interface need to have several different appearances, or ‘states’. We find ourselves having to do a lot more, with the same amount of markup.

Managing all these states is something that can quickly get out of hand with large applications. I’ll go over how I manage elements with several states, and some of the best practices I have developed.

Building on a default appearance

Every element has to have a default appearance; this is the appearance when no overriding ‘state styles’ are in affect. I have found it most useful to start with the smallest ‘mobile’ view first, and then progressively enhancing the element by adding more styles as more states take affect, this is commonly know as the ‘mobile first’ approach.

The ‘scattered’ approach

The approach I strongly advise against is the ‘scattered everywhere’ approach. By this I mean you may find your default styling for an element in its file (eg. header.scss), then throughout the application you find rules in other files that manipulate this default styling. The all too common mobile.scss and ie.scss spring to mind here.

You have rules that style one particular element, all over your CSS code base. There is no one place a new developer can go to see an overview of the styling for a single element, they have no way of knowing about rules that may be hiding in other files. It also means that your cascade order is at the whim of the order the files are concatenated in. It’s all dangerous stuff!

The centralised approach

I enforce the convention that all styles for a particular element must be in one central place. When I’m styling up an element I want to be able to:


  See at a glance all the different ‘states’ it can be in
  Easily compare the specificity of different rules
  Quickly shift the cascade order or styles


This isn’t possible if rules are scattered over many files.

Coding style

I use SASS nesting, the &amp;amp; parent selector to visually contain all the style variations for a particular element. I also use an @state comments to clearly indicate where I’m overriding default styling. Let me demonstrate with an example.

.login-button {
  padding: 10px;
  background: pink;

  /**
   * @hover
   */

  &amp;amp;:hover {
    background: red;
  }

  /**
   * @large
   *
   * The button is bigger
   * on large screens.
   */

  @media (min-width: 700px) {
    padding: 20px;
  }

  /**
   * @logged-in
   *
   * The button is hidden
   * when the 'logged-in'
   * class is on the &amp;lt;body&amp;gt;
   */

  .logged-in &amp;amp; {
    display: none;
  }
}

What we end up with here is a encapsulated bundle for each element in our application. All the rules inside this bundle only concern a single element.

You can be quicker and more confident in your refactoring, and new team members can comfortably work on a small part of an application, without having to know the whole thing.


  I’m interested to find out how others tackle this problem, drop a comment if you have any useful tips!

</description>
        <pubDate>Tue, 29 Oct 2013 23:00:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/styling-states-in-css/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/styling-states-in-css/</guid>
      </item>
      
    
      
      <item>
        <title>Sensible CSS</title>
        <description>Every developer can write CSS, the hard part is keeping things manageable as your app starts to grow.

Over the past two years I’ve been writing CSS for several large web applications. I’ve been fortunate enough to be the primary maintainer of these code bases, which has given me free reign to try out various approaches in an attempt to keep things sensible. In this post I will will share some of my techniques which I feel really made a difference.

1. Preprocessors

If there’s one single thing that really made my life easier it’s preprocessors. We chose to use SASS on the projects I worked on. I had used LESS in the past, but chose to start using SASS mainly because it’s all I ever heard other CSS devs talk about, and also due to this post by Chris Coyier.

Aside from which preprocessor you choose to use, I will become your closest ally in helping you to fight the battle for sensible CSS. The tips that follow will assume that you are using a preprocessor. Examples will be in SASS, but most should be easily transferable to other languages.

2. Standard padding

Throughout our app we need to use padding and margins to space things out. In apps I’ve worked on in the past these values have all to often just been random pixel values that looked close to the mockup at the time.

Keep all spacing in your app looking consistent by introducing padding variables. I like to keep these ‘app wide’ variables in a single file called vars.scss.

$padding: 14px;
$padding-200: $padding * 2;
$padding-150: $padding * 1.5;
$padding-75: $padding * 0.75;
$padding-50: $padding * 0.5;

Throughout your app make it a rule that every padding or margin definition must use the standard variables.

.header {
  padding: $padding;
  margin-bottom: $padding-200;
}


  If you’re targeting relatively modern browsers, or aren’t using a pre-processor, you could also look at using rem units to do something similar.


html {
  font-size: 14px;
}

.header {
  padding: 1rem;
  margin-bottom: 2rem;
}

3. Standard colours

Every professional application has a colour pallet. Don’t bother typing those horrible hex codes all over your app. Instead define them in once inside your vars.scss file and use the variables throughout your app code.

$color-blue: #4781AA;
$color-blue-dark: #002F5F;
$color-dark-text: #333;
$color-medium-text: #505050;
$color-light-text: #777;
$color-pink: #FFF1E0;
$color-claret: #9E2F50;
$color-pink-tint-1: #F6E9D8;
$color-pink-tint-2: #E9DECF;
$color-warm-grey-1: #A7A59B;
$color-warm-grey-2: #74736C;

It’s now a breeze if your designer wants to alter the color pallet slightly.

Nesting

With CSS preprocessors comes the ability to nest selectors. With all new things, it’s easy to get carried away. I like to keep it to a minimum, attempting not to nest deeper than three levels. I name my classes in a way that means that I can write really short, specific selectors.

This is good for selector matching performance (negligible) and means elements remain portable. By ‘portable’ I mean that if markup changes slightly, you don’t have to go through altering selectors that were previously very specific, so that they match the new document structure.

File structure

The first step to sensible CSS is keeping files as short as possible. I want each file to cover a very specific part of my application, there should be no rules inside that file that do not concern that part.

Let’s have a look at a fictitious header.scss file as an example.

.header {
  background: red;
}

I know what you’re thinking: ‘this is ludicrous, an entire file for one CSS rule!’. Relax…this this is fine! We’re using a preprocessor that will combine all these files into one file, so there really is no overhead to creating more files. I’ve worked on projects with 100 - 150 .scss files, and it was one of the most effective ways of keeping things manageable.

What we’re getting here is ‘separation of concern’, and this is super valuable! Although right now our header.scss file is really short, who knows how it will evolve over the course of the applications life. Whenever I start styling a new part of an application, the first thing I do is create a new file for it. The more files you have, the better!

Selector order

Not all the files in you application are going to be as short as header.scss above. When files do begin to grow, it is important to structure them consistently so devs know where to find rules. To help with this, I stick by the simple convention of ordering my selectors in the same order that they appear in the markup.

If the markup looks like this,

&amp;lt;header class=&quot;header&quot;&amp;gt;
  &amp;lt;ul class=&quot;header_links&quot;&amp;gt;...&amp;lt;/ul&amp;gt;
  &amp;lt;input class=&quot;header_search&quot; type=&quot;search&quot; /&amp;gt;
&amp;lt;/header&amp;gt;

… the corresponding stylesheet should look like this,

.header {}
.header_links {}
.header_search {}

Styling state

At some point you’re going to have to override the default styling of an element when your app is in a specific state. ‘State’ could be anything, but I’ll use the simple example of a disabled button. Our default styling for the button is active, then we have a selector that overrides the default appearance to give it a ‘disabled’ appearance. One way of structuring this that I’m sure you’ve all come across is this:

.my-button {
  background: red
}

/* 1000 lines later or in another file */

.my-button[disabled],
.my-other-thing[disabled] {
  opacity: 0.5;
  pointer-events: none;
}

This is a nightmare. If I’ve be given the task to work on .my-button I want to go the the initial selector and see all the possible states that element can be in, in one place. I am then able to make informed judgements when taking care of my task.

/** My Button
 ---------------------------------------------------------*/

.my-button {
  background: red
}

/**
 * [disabled]
 */

.my-button[disabled] {
  opacity: 0.5;
  pointer-events: none;
}

I also included a handy divider that gives pre-warning to other developers that I’m defining a stateful override based on the [disabled] attribute.


  I wrote a more detailed post on ‘Styling state in CSS’


JS only classes

One of the tricky things about classes is that they may not only be being used for styling, they could be being used in JavaScript too. This can make refactoring markup a daunting process, you want to tidy everything up, but changing a class name that JavaScript is dependent on could take down your whole app.

A convention of ‘Javascript specific classes’ that Nicolas Gallagher wrote about has proven to work really well. In our markup we have two types of classes, styling classes and JavaScript classes. It is clear when a class is a JavaScript class as it is prefixed with js-.

&amp;lt;input class=&quot;header_search js-search&quot; type=&quot;search&quot; /&amp;gt;

When were want to select the element in JavaScript we use the js-search class.

var el = document.querySelector('.js-search');

In CSS we use the un-prefixed class. Styling using the js-* classes is strictly forbidden.

.header_search {
  /* styles */
}

Avoid ‘globals’

In JavaScript it is common knowledge that polluting the global scope with variables is bad practice, in CSS it is less well known. I’ve inherited projects where I have spent months battling against global styles, let me give an example,

button {
  margin-bottom: 20px;
}

By writing the above CSS the developer has made the assumption that every &amp;lt;button&amp;gt; element in the application must have the following styles. Now every-time I want to use a button element I find myself reseting these styles.

.my-button {
  margin-bottom: 0;
}

If we have third-party widgets in our app, they too will be impacted by these global styles.

I usually try to avoid tag selectors, but if they must be used, I use a direct-child selector (&amp;gt;) to ensure these styles don’t leak where they’re not wanted.

.my-container &amp;gt; button {
  margin-bottom: 20px;
}

Summary

We’ve all experienced a CSS nightmare at some point; it takes discipline and conventions to keep everything sane. I’ve tried a lot of things, some worked, some didn’t. In this article I’ve tried to distill ‘the best bits’. Drop a comment if you’ve discovered techniques that help maintain your sanity.
</description>
        <pubDate>Tue, 29 Oct 2013 16:00:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/sensible-css/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/sensible-css/</guid>
      </item>
      
    
      
      <item>
        <title>Batching image insertion</title>
        <description>One of the most expensive things we do inside our app is insert base64 encoded images into the DOM. You can easily blow your frame budget (16ms) if you try to insert too many images in one go. Below is a timeline showing one particular frame being smashed when a load of images get inserted into the DOM.



In this simplified version of the code, we have a list of image objects. We loop over these objects, create an image node for each, set the src to the base64 data URI string, and then insert it into the DOM.

images.forEach(inject);

function inject(image) {
  var el = document.createElement('img');
  el.src = image.src;
  document.body.appendChild(el);
}

Spreading the load

The technique above doesn’t scale. The more images we have to insert, the worse our rendering performance gets. If we could find a way to take work off this single frame and spread it over more frames, we may be able to reach a better frame rate. FastDom can help us with this.

fastdom.defer()

FastDom’s .defer method allows us to defer work until the next available animation frame.

fastdom.defer(function() {
  // This will run in frame 1
});

fastdom.defer(function() {
  // This will run in frame 2
});

fastdom.defer(function() {
  // This will run in frame 3
});

This is super useful when you want to spread load over several frames. So to improve the performance of our image insertion we will first break the list into batches, and then insert them inside a fastdom.defer job.

var batchSize = 6;
var batch;

// Break down list into batches
for (var i = 0, l = placeholders.length; i &amp;lt; l; i += batchSize) {
  batch = images.slice(i, i + batchSize);
  injectBatch(batch);
}

// Schedules a batch
// for the *next* frame
function injectBatch(batch) {
  fastdom.defer(function() {
    batch.forEach(inject);
  });
}

// Injects an image
function inject(image) {
  var el = document.createElement('img');
  el.src = image.src;
  document.body.appendChild(el);
}

Now our timeline looks a little different. You can see that the expensive image work is spread over about five frames instead of one, and we are not longer blowing the 60fps threshold.



Batch size

In my example I used a batch size of 6. This isn’t a magic number, I simply used the timeline to determine an appropriate number for my case. You should profile your own image insertion and find a batch size you’re happy with.

Conclusion

This is just one of the useful applications for the FastDom’s .defer API. Timeline your app and check for where you are blowing your frame budget.

If you’re ‘layout thrashing’ you should look into fastdom.read and fastdom.write, if you’re simply doing too much in one frame think about spreading your work over several frames.
</description>
        <pubDate>Wed, 23 Oct 2013 19:09:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/batching-image-insertion/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/batching-image-insertion/</guid>
      </item>
      
    
      
      <item>
        <title>Return early</title>
        <description>One of my pet hates in JavaScript is code nested inside deep ifs and elses. It seems to make functions a lot harder to follow, and nine times out of ten can be avoided. I’ll try to demonstrate by showing a few before and after examples.

Nested if else

function myFunction(value) {

  if (value === 'thing') {
    // do stuff to 'thing'
  } else {
    // if it's not 'thing'

    if (value === 'other thing') {
      // do stuff to 'other thing'
    } else {
      // if it's not 'other thing' do stuff
    }
  }
}

Could be re-written like

function myFunction(value) {

  if (value === 'thing') {
    // do stuff to 'thing'
    return;
  }

  if (value === 'other thing') {
    // do stuff to 'other thing'
    return;
  }

  // if it's not 'other thing' do stuff
}

Large if blocks

It is common that we need to address two different code paths in one function. I often see code where the the majority of the function is nested inside an if or else block. By the time we have got to the else, we have forgotten what the condition was in the first place.

function myFunction2(value) {

  if (value !== 'thing') {

    // 1. Do this
    // 2. then this

    // 3. then this
    // 4. then this
    // 5. then this

    // 6. then this
    // 7. then this
    // 8. then this

    // 9. then this
    // 10. then this

    if (value === 'foo') {
      // Do stuff when 'foo'
    }

  } else {

    // The vlaue isn't 'thing'
    // and we need to do something
    // slightly different.
  }
}

By returning early we can address the edge cases and anomalies before we get to the core logic. Every time we return, we are starting from a clean slate. The reader no longer has to hold all that state in their memory…relief!

function myFunction2(value) {

  if (value === 'thing') {
    // The vlaue isn't 'thing'
    // and we need to do stuff
    return;
  }

  // 1. Do this
  // 2. then this

  // 3. then this
  // 4. then this
  // 5. then this

  // 6. then this
  // 7. then this
  // 8. then this

  // 9. then this
  // 10. then this

  if (value === 'foo') {
    // Do stuff when 'foo'
  }
}

Conclusion

The best type of code we can write is code that others’ can quickly understand and contribute to. I’m always looking for ways to make my logic as simple to follow as possible.

Each nested block demands an allocation of short-term memory from the reader’s brain. As the reader dives deeper and deeper into nested blocks they will eventually blow their capacity, and lose their train of thought.

If we avoid nesting, we make our code easier to read. If code is easier to read, more people can contribute, and bugs can be more easily spotted.


  I’m looking to add more examples of how returning early can simplify logic, if you have any, please say so and I will add them to this post.

</description>
        <pubDate>Wed, 23 Oct 2013 09:17:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/return-early/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/return-early/</guid>
      </item>
      
    
      
      <item>
        <title>Math.min and Math.max</title>
        <description>You’ve probably heard of and used the Math.min and Math.max functions in JavaScript before, they’re pretty self explanatory.

Math.min(5, 10); //=&amp;gt; 5
Math.max(5, 10); //=&amp;gt; 10

Something useful

One trick that I found particularly handy, is when using both Math.min and Math.max together to constrain a number between two bounds.

var min = 5;
var max = 10;

Math.max(min, Math.min(15, max)); //=&amp;gt; 10
Math.max(min, Math.min(2, max)); //=&amp;gt; 5
Math.max(min, Math.min(7, max)); //=&amp;gt; 7

Something to take-away

We can use ‘currying’ to create a dynamic constraining function that will constrain numbers to the specified bounds.

function constrainer(min, max) {
  return function(n) {
    return Math.max(min, Math.min(n, max));
  };
}

var constrain = constrainer(5, 10);

constrain(15); //=&amp;gt; 10
constrain(2); //=&amp;gt; 5
constrain(7); //=&amp;gt; 7

Demo
</description>
        <pubDate>Tue, 22 Oct 2013 22:17:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/math-min-and-math-max/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/math-min-and-math-max/</guid>
      </item>
      
    
      
      <item>
        <title>Animation iteration event</title>
        <description>In the past I have used CSS Animations to roll my own loading spinners. I prefer using CSS animations as I can get a smoother frame rate, without the need for any clunky gif assets.

div.spin {
  animation: spin 1000ms linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg) }
  100% { transform: rotate(360deg) }
}

One thing that has always bothered me about this is that once the loading has finished and we remove the spin class, the animation would abruptly jump back to its starting position (0deg).

A helpful event

The animationiteration event will fire every time a currently animating element completes an iteration.

div.addEventListener('animationiteration', function() {
  console.log('tick');
});

Solving the problem

We can use this event to remove our spin class at exactly the right time so that our animation doesn’t jump back to the start when loading has finished.

function start() {
  div.classList.add('spin');
}

function stop() {
  div.addEventListener('animationiteration', callback);

  function callback() {
    div.classList.remove('spin');
    div.removeEventListener('animationiteration', callback);
  }
}

Browser support

The animationiteration event is well supported in modern browsers using the following prefixes.


  
    
       
       
    
  
  
    
      W3C Standard
      animationiteration
    
    
      Firefox
      animationiteration
    
    
      Webkit
      webkitAnimationIteration
    
    
      IE10
      MSAnimationIteration
    
  


Demo
</description>
        <pubDate>Thu, 10 Oct 2013 09:31:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/animation-iteration-event/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/animation-iteration-event/</guid>
      </item>
      
    
      
      <item>
        <title>Redirecting posts from Tumblr</title>
        <description>As you may know I have recently migrated my blog from Tumblr to a custom Jekyll solution hosted on GitHub Pages. My main issue was redirecting traffic from old links to my new domain and URL schema. The URL changed as follows:

wilsonpage.tumblr.com/posts/&amp;lt;POST-ID&amp;gt;/&amp;lt;POST-TITLE&amp;gt; =&amp;gt; wilsonpage.co.uk/&amp;lt;POST-TITLE&amp;gt;

For obvious reasons Tumblr doesn’t really help you redirecting away from their site. This means we have two solutions:


  JavaScript redirects (window.location.href = 'http://example.com';)
  Meta refresh redirects (&amp;lt;meta http-equiv=&quot;refesh&quot; content=&quot;0;'http://example.com'&quot; /&amp;gt;)


The former is not ideal as crawlers/bots are unlikely to follow JavScript redirects. The later is tricky as tumblr doesn’t give me the ability to manipulate strings in their templating language to allow me to transform the Tumblr URL into my new URL. I needed the ability to dynamically transform the URL on the server-side, or just manually define a server-side variable containing the new URL for each post.

My solution

The only variables I could define myself were the post Title and Body. I decided to abuse the Post Title as my own custom variable.



I can use my custom variable inside the page html template as the URL path inside the meta refresh tag.



If the page is a post page the user is redirected to wilsonpage.co.uk/&amp;lt;POST-TITLE&amp;gt;. If it’s not a post page, they are simply redirected to wilsonpage.co.uk. It doesn’t really matter that the Tumblr post titles are not as pretty now, as no-one will be reading them anyway.

I think this is an adequate work around for the lack of URL migration facilities from Tumblr. Fortunately this didn’t require much work on my part as I didn’t have that many posts to migrate. Over time there will be fewer old links in the wild, and I should be able to close the Tumblr blog all together. The most important thing is that old links continue to arrive at my content.
</description>
        <pubDate>Tue, 01 Oct 2013 10:29:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/redirecting-posts-from-tumblr/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/redirecting-posts-from-tumblr/</guid>
      </item>
      
    
      
      <item>
        <title>Object.create</title>
        <description>Object.create() returns a new object with a prototype of the object you passed it.

var proto = { foo: 'bar' };
var newObject = Object.create(proto);

newObject.foo; //=&amp;gt; 'bar'
newObject.hasOwnProperty('foo'); //=&amp;gt; false

Inheritance

var o1 = { one: '1' };

var o2 = Object.create(o1);
o2.two = '2';

var o3 = Object.create(o2);
o3.three = '3';

var o4 = Object.create(o3);

Results in a prototype chain like:



Which means we can do:

o4.one; //=&amp;gt; 1
o4.two; //=&amp;gt; 2
o4.three; //=&amp;gt; 3

What about the second argument?

The second argument is not too exciting; it works as a convenient shortcut to Object.defineProperties(). In short Object.defineProperties allows you to define the properties of particular keys on your object.

I won’t go over the API for Object.defineProperties in this article, but you can read all about it on our ever trustworthy MDN.

Demo
</description>
        <pubDate>Mon, 30 Sep 2013 22:05:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/object-create/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/object-create/</guid>
      </item>
      
    
      
      <item>
        <title>JavaScript inheritance</title>
        <description>Inheritance is the process of generating a new class that is based on (or extends from) the properties of an existing class. JavaScript doesn’t offer inheritance out of the box, but with just four lines of code we can make our own inheritance method. I will will introduce this technique, and attempt to explain simply how it works.

function inherit(A, B) {
  function F(){} // 1.
  F.prototype = A.prototype; // 2.
  B.prototype = new F(); // 3.
  B.prototype.constructor = B; // 4.
}

What’s going on here?

Above we have defined a method that accepts two constructor functions. A represents the base class which we a extending from, and B represents the class which will extend from A. The routine goes as follows:


  Create a new temporary function.
  Overwrite the temporary function’s prototype object with A’s prototype object.
  Overwrite B’s prototype object with an instance of the temporary class F. This means B’s protype is now an empty object with it’s own prototype…A.prototype, we have extended the ‘prototype chain’.
  B’s direct prototype now no longer has a constructor property, so, incase anyone wants to use this property, we must re-set it.


Usage

// Create a base class
// with a generic method
function Animal(){};
Animal.prototype.eat = function(){ return 'eating'; };

// Define another class
function Bird() {}

// Manipulate the `Bird`
// class’s prototype to
// extend from `Animal`
inherit(Animal, Bird);

// Add a Bird specific
// property to the prototype
Bird.prototype.fly = function(){ return 'flying'; };

// Create a bird
var bird = new Bird();

// Test that bird has both
// the `Animal` properties
// and the `Bird` properties
bird.eat(); //=&amp;gt; eating'
bird.fly(); //=&amp;gt; 'flying'

// Test that bird is both an
// instance of `Animal` and `Bird`
bird instanceof Animal; //=&amp;gt; true
bird instanceof Bird; //=&amp;gt; true

The prototype chain

Under the hood all we’re doing is extending the Animal.prototype, adding a new object to the top of the chain and defining additional properties on that object. In this case the chain looks as follows:

Bird &amp;lt;= Animal &amp;lt;= Object



When a property is accessed on the instance, the JS runtime will check each layer of the prototype (shallowest to deepest) until the property is found. If the property is not found on the last layer of the prototype, undefined is returned.

NOTE: There are performance issues that come from extending the prototype chain too far. I’ve found there is rarely reason to be extending more than one layer deep. Keep the inheritance chain as short as possible.

Object.create()

This is just one of the many techniques out there when implementing an inheritance style pattern in JavaScript. Since ES5 Object.create has been available and can simplify the process even further.

function inherit(A, B) {
  B.prototype = Object.create(A.prototype);
  B.prototype.constructor = B;
}

Conclusion

In my experience I’ve found very few cases that genuinely require inheritance. It can sometimes seem like a good idea at the time, but in the long run can end up over complicating things. My advice for most cases would be: try to use composition over inheritance, keep relationships simple.
</description>
        <pubDate>Sun, 22 Sep 2013 07:57:19 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/javascript-inheritance/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/javascript-inheritance/</guid>
      </item>
      
    
      
      <item>
        <title>Preventing 'layout thrashing'</title>
        <description>Layout Thrashing occurs when JavaScript violently writes, then reads, from the DOM, multiple times causing document reflows.

// Read
var h1 = element1.clientHeight;

// Write (invalidates layout)
element1.style.height = (h1 * 2) + 'px';

// Read (triggers layout)
var h2 = element2.clientHeight;

// Write (invalidates layout)
element2.style.height = (h2 * 2) + 'px';

// Read (triggers layout)
var h3 = element3.clientHeight;

// Write (invalidates layout)
element3.style.height = (h3 * 2) + 'px';

When the DOM is written to, layout is ‘invalidated’, and at some point needs to be reflowed. The browser is lazy and wants to wait until the end of current operation (or frame) to perform this reflow.

Although, if we ask for a geometric value back from the DOM before the current operation (or frame) is complete, we force the browser to perform layout early, this is known as ‘forced synchonous layout’, and it kills performance!

The side effects of layout thrashing on modern desktop browsers is not always obvious; but has severe consequences on low powered mobile devices.

Quick fix?

In an ideal world we would simply re-order the execution so that we can batch the DOM read and DOM writes together. This means the document only needs to be reflowed once.

// Read
var h1 = element1.clientHeight;
var h2 = element2.clientHeight;
var h3 = element3.clientHeight;

// Write (invalidates layout)
element1.style.height = (h1 * 2) + 'px';
element2.style.height = (h2 * 2) + 'px';
element3.style.height = (h3 * 2) + 'px';

// Document reflows at end of frame

What about in the real world?

In reality this isn’t so simple. Large applications have code scattered all over the place, all of which has that dangerous DOM at its finger tips. We can’t easily (and definitely shouldn’t) mash up all our pretty, decoupled code, just so we have control over execution order. What can we do to batch our reads and writes together for optimal performance?

Enter requestAnimationFrame

window.requestAnimationFrame schedules a function to be executed at the next frame, similar to setTimeout(fn, 0). This is super useful because we can use it to schedule all our DOM writes to run together in the next frame, leaving all DOM reads to run in the current synchronous turn.

// Read
var h1 = element1.clientHeight;

// Write
requestAnimationFrame(function() {
  element1.style.height = (h1 * 2) + 'px';
});

// Read
var h2 = element2.clientHeight;

// Write
requestAnimationFrame(function() {
  element2.style.height = (h2 * 2) + 'px';
});

This means we can keep our nicely encapsulated code where it is, and with a small code tweak, batch our pricey DOM access together! Win!

Working example

I created a working example to prove the concept. In the first screen shot you can see the aggressive layout thrashing in the Chrome Timeline.


  
    
      Before
      After
    
  
  
    
      
      
    
  


Following our requestAnimationFrame alterations only one layout event took place, and as a result the operation was ~96% faster!

Can this scale?

In a simple example using raw requestAnimationFrame does allow us to postpone DOM writes to greatly improve performance, but this technique just doesn’t scale.

In our app we may need to read from the DOM after we have done our write, and then we are in layout thrashing territory again, just in a different frame.

// Read
var h1 = element1.clientHeight;

// Write
requestAnimationFrame(function() {
  element1.style.height = (h1 * 2) + 'px';

  // We may want to read the new
  // height after it has been set
  var height = element1.clientHeight;
});

We could push the read into another requestAnimationFrame but then we cannot guarantee another part of the app has not just pushed a write job into the same frame. Essentially it’s all going to get a bit chaotic, and once again you no longer have control over when DOM read/writes are happening.

Introducing ‘FastDom’

FastDom is a small library I wrote to provide a common interface for batching DOM read/write work. It massively speeds up DOM work using similar requestAnimationFrame techniques described above.

fastdom.read(function() {
  var h1 = element1.clientHeight;
  fastdom.write(function() {
    element1.style.height = (h1 * 2) + 'px';
  });
});

fastdom.read(function() {
  var h2 = element2.clientHeight;
  fastdom.write(function() {
    element2.style.height = (h1 * 2) + 'px';
  });
});

FastDom harmonises DOM interactions by taking read and write jobs and batching them (reads then writes) on the next frame. This means you can build app components in isolation without worrying how they will affect (or be affected) by other components in the app.

Implications of using FastDom

By using FastDom you are making all DOM tasks asynchronous, that means you can’t always make assumptions as to what state the DOM will be in. Work that was previously sync, may not have completed now it is async.

To work around this I like to use an event system to be more explicit about when work has finished, and responding only when I know DOM work I’m dependent on is complete.

Also we are increasing the amount of code we have to write to effectively get the same amount of work done. Personally I think this is a small price to pay for a dramatic increase in performance.

FastDom examples


  Animation example
  Aspect ratio example


Improving FastDom

Web apps are lacking a clear way of solving the problem of layout thrashing. As an app grows it gets harder to coordinate all the different parts to ensure a fast end product. If FastDom can help provide a simple interface for developers to solve this problem, it can only mean good things.

Have a look at the FastDom project  and feel free to contribute by submitting pull requests or filing issues.
</description>
        <pubDate>Thu, 19 Sep 2013 12:00:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/preventing-layout-thrashing/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/preventing-layout-thrashing/</guid>
      </item>
      
    
      
      <item>
        <title>matchMedia is cooler than you think</title>
        <description>Most of you will have heard about window.matchMedia. It’s a relatively simple API that accepts a string in the form of CSS @media query.

var result = window.matchMedia('(min-width:400px)');

We can see if the media query passed currently matches by inspecting the result.matches property. Pretty dull hey…? But things get a little more interesting when we realise that the object returned is actually live.

The result.matches boolean will update whenever the media query condition matches or un-matches. Best of all we have a way of listening for when this change has occurred. Let’s have a closer look at the object returned from window.matchMedia.

The mediaList object


  matches {Boolean} Declares whether the media query currently matches.
  media {String} The media query string that was originally passed.
  addListener {Function} A method to attach a callback to fire when the matches state changes.
  removeListener {Function} A method to remove a previously registered callback.


Listening for changes

We now have means by which we can run code when the window enters or leaves declared breakpoints. This is super useful when we are building parts of our app that not only new to look different at different screen sizes, but also need to behave differently.

var media = window.matchMedia('(min-width: 500px)');

media.addListener(function(data) {
  alert('matches: ' + data.matches);
});

Demo

I whipped up a quick demo that shows how you can setup and teardown component states by responding to matchMedia callbacks.

View demo
</description>
        <pubDate>Wed, 18 Sep 2013 18:16:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/matchmedia-is-cooler-than-you-think/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/matchmedia-is-cooler-than-you-think/</guid>
      </item>
      
    
      
      <item>
        <title>Git in color</title>
        <description>By default git has no coloured output. Quickly improve the situation with:

$ git config --global --add color.ui auto
</description>
        <pubDate>Mon, 19 Aug 2013 19:31:19 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/git-in-color/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/git-in-color/</guid>
      </item>
      
    
      
      <item>
        <title>Introducing 'layout boundaries'</title>
        <description>‘Layout’ is the process a browser undergoes to calculate the position and size of each element in a document before it can start painting pixels. The process of layout can be costly, especially on low powered mobile devices.

As considerate front-end developers, it is our job to keep layouts to minimum to ensure our apps remain snappy.At some point though, layout has to be done. DOM structure changes, changes to dimensions or position of elements, and requests for element position or size via JavaScript, can all trigger layout.

What is not commonly known, is that layouts events have scope. Most of the time a layout forcing change to one small part of your app, will cause the entire document to be reflowed; and this can mean thousands of nodes.

Introducing ‘layout boundaries’

With a few small CSS tweaks we are able to enforce layout boundaries in our document. This means that if any layout forcing changes are made inside the scope of a layout boundary element, only a ‘partial reflow’ is required, and this is a lot cheaper!

To be a layout boundary, the element must:


  Be an SVG root (&amp;lt;svg&amp;gt;).
  Be a text or search &amp;lt;input&amp;gt; field.


or:


  Not be display inline or inline-block
  Not have a percentage height value.
  Not have an implicit or auto height value.
  Not have an implicit or auto width value.
  Have an explicit overflow value (scroll, auto or hidden).
  Not be a descendant of a &amp;lt;table&amp;gt; element.


Paul Lewis’ Boundarizr tool can be used to highlight which elements in your app are acting as ‘layout boundaries’.

Facebook example

To prove my point I have found a layout case on Facebook that could be optimised. When the auto-complete search drop-down is opened we can see in the timeline quite aggressive layout thrashing as elements are inserted and manipulated in the list.

By hovering over the layout event in Chrome Devtools Timeline we can see that the ‘Layout scope’ is labeled as ‘Whole document’ (highlighted in blue), the ‘Layout tree size’ is 2551 nodes, and the ‘Duration’ is 2.142ms.



Diving into the Elements panel I find a suitable parent node above where the DOM changes are taking place. I set a pixel based height, and set overflow: hidden. The element is already position: absolute, and already has a width set, so I don’t have to introduce those changes.

This should enforce a layout boundary to scope the reflow to a much smaller portion of the document.



I now run the same routine and observe the layout events again in the Timeline panel.



When we hover over the layout event we can see the blue highlighted area now only covers our newly promoted ‘layout boundary’ element. The ‘Layout scope’ is now labeled as ‘partial’, the ‘Layout tree size’ is 228 nodes (91% reduction) and the Duration is 1.255ms (41% reduction).

Is this a micro-optimisation?

In terms of duration per layout event a saving of ~1ms seems pretty negligible, but let’s take a few more points into consideration:


  This event was one of about 20 similar events that were triggered when the drop-down menu was revealed, and each one gained a similar saving following the CSS tweak.
  We are profiling this on a high powered MacBook Air within Google Chrome. The speed of layout within this type of environment greatly outperforms that of even the most performant mobile devices. If we are reducing layout time by 40%, the gains on devices that are slower at layout could be significant.
  This particular layout is relatively simple. Within a more complex (flexbox, tables, floats, etc) layout we would likely see greater gains.


How does this work?

TBH I’m not 100% sure. I would guess that by constraining the size of the parent element and making sure descendent elements cannot flow out of the boundaries by setting overflow: hidden;, layout engine optimise by making the assumption that nodes outside the layout boundary do not have to be checked.

Is this just applicable to Chrome?

TBH I’m not sure, but I would guess that other browser layout engines would make similar optimisations when element style properties permit.

At the time of writing (AFAIK) we don’t have the same level of layout profiling available to us within other browser’s developer tools.

If there are ways we can measure this inside browsers other than Chrome I would love to hear about it :)

Conclusion

To me this seems like something we should really be considering more in development. If we can make some super quick style changes that enforce layout boundaries, the browser has to do less work, and we get faster layout times.

Try it out in your app and let us know if you are able to make some quick performance gains.
</description>
        <pubDate>Sun, 18 Aug 2013 19:31:19 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/introducing-layout-boundaries/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/introducing-layout-boundaries/</guid>
      </item>
      
    
      
      <item>
        <title>Touch events in Chrome Android</title>
        <description>Today I came across some odd behaviour in Chrome Android. In our app we have a module that is responsible for listening for user touch events and responding by panning or swiping to the next page.

In Chrome Android our ‘touchmove’ event callback seemed not to be firing at all, and as a result the panning and swiping feature of our app was broken. After doing a quick timeline in Chrome Dev Tools I could see three events firing: ‘touchstart’, ‘touchmove’ and ‘touchcancel’. Wait … ‘touchcancel’ wat?!

I sent out a plea for help on Twitter, thankfully https://twitter.com/gauntface (Google Chrome) sent me this advice:


@wilsonpage There is a 200ms delay that you need to call e.preventDefault() in. However, the 200ms delay is dependant the time the system ..
&amp;mdash; Matt Gaunt (@gauntface)
August 7, 2013



Why was Chrome cancelling my touch events?

From https://code.google.com/p/chromium/issues/detail?id=260732, it seems as though it’s for performance reasons. Chrome probably wants to handle the touches for browser default events such as scrolling without the complication of handling any custom logic.

What’s the problem?

In order to listen to the touch events in Chrome Android I have to call event.preventDefault();. If I ‘prevent default’ I am effectively say to the browser “leave this event alone, I’m handling it”.

This is fine, except we now lose the option of native overflow: scroll; within any element that may reside within the element I’m listening for touches on. Preventing default on a ‘touchstart’ or ‘touchmove’ event will prevent any scrolling that would have been handled by the browser from occurring.

In my app I wanted horizontal panning and swiping of pages to be handled by JavaScript and vertical scrolling to handled natively by overflow: scroll; or -webkit-overflow-scrolling: touch. In Chrome Android (unlike other browsers) this is appears not to be possible.

A work around

To achieve the desired result I will now have to use synthetic JavaScript powered scrolling for both horizontal panning and swiping as well as vertical scrolling. I may choose to do this just for Chrome Android so as to get the performance benefits of native scrolling on other platforms.

Looking forward

I understand handling custom and default responses to touch event must be a tricky one to manage for browsers. I’m just writing this up to highlight a use case that requires both responses. Microsoft’s [http://msdn.microsoft.com/en-us/library/windows/apps/hh767313.aspx](-ms-touch-action) property from the http://www.w3.org/Submission/pointer-events/ does a good job giving developers control over how touches are handled by the browser, and could end up working its way into the other major browsers.
</description>
        <pubDate>Thu, 08 Aug 2013 12:24:00 +0000</pubDate>
        <link>http://blog.wilsonpage.co.uk/touch-events-in-chrome-android/</link>
        <guid isPermaLink="true">http://blog.wilsonpage.co.uk/touch-events-in-chrome-android/</guid>
      </item>
      
    
  </channel>
</rss>