ReactJS Refs

ReactJS Refs

ReactJS provides a mechanism for referencing the actual component instance by using the refs property:

1
2
3
4
5
6
7
8
9
10
11
12
13
var App = React.createClass({
  handleClick: function () {
    console.log(this.refs.input.getDOMNode().value);
  },
  render: function () {
    return (
      <div>
        <input ref="input" />
        <button onClick={this.handleClick}>Submit</button>
      </div>
    );
  }
});

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var App = React.createClass({
      getInitialState: function() {
        return {
          red: 0,
          green: 0,
          blue: 0
        }
      },
      update: function(e) {
        this.setState({
          red: this.refs.red.refs.inp.getDOMNode().value,
          green: this.refs.green.refs.inp.getDOMNode().value,
          blue: this.refs.blue.refs.inp.getDOMNode().value
        });
      },
      render: function() {
        return (
          <div>
            <Slider ref="red" txt={this.state.txt} update={this.update} />
            <label>{this.state.red}</label>
            <Slider ref="green" txt={this.state.txt} update={this.update} />
            <label>{this.state.green}</label>
            <Slider ref="blue" txt={this.state.txt} update={this.update} />
            <label>{this.state.blue}</label>
          </div>
        );
      }
    });

    var Slider = React.createClass({
      render: function() {
        return (
            <div>
              <input ref="inp" type="range" min="0" max="255" onChange={this.props.update} />
            </div>
        );
      }
    });

    React.render(<App txt="this is the txt prop" />, document.body);
  </script>
</body>
</html>

So far so good, That’s it!!! See ya!!! :)

ReactJS Ownership

ReactJS Ownership

In React, an owner is the component that sets the props of other components. More formally, if a component X is created in component Y’s render() method, it is said that X is owned by Y.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var App = React.createClass({
      getInitialState: function() {
        return {
          txt: ''
        }
      },
      update: function(e) {
        this.setState({txt: e.target.value});
      },
      render: function() {
        return (
          <div>
            <Widget txt={this.state.txt} update={this.update} />
            <Widget txt={this.state.txt} update={this.update} />
          </div>
        );
      }
    });

    var Widget = React.createClass({
      render: function() {
        return (
          <div>
            <input type="text" onChange={this.props.update} />
            <br />
            <b>{this.props.txt}</b>
          </div>
        );
      }
    });

    React.render(<App txt="this is the txt prop" />, document.body);
  </script>
</body>
</html>

The example above Widget component is owned by App component.

So far so good, That’s it!!! See ya!!! :)

ReactJS State

ReactJS State

What is State?

The state object is internal to a component. It holds data which can change over time. So far, we’ve used ReactJS as a static rendering engine. Now, we’re going to add state to make React components more dynamic.

The key difference between props and state is that state is internal and controlled by the component itself while props are external and controlled by whatever renders the component. Let’s see it in practice:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var Profile = React.createClass({
      getInitialState: function() {
        return {
          name: 'Bunlong'
        };
      },
      onNameInput: function(e) {
        this.setState({name: e.target.value});
      },
      render: function() {
        return (
          <div>
            <input type="text" onChange={this.onNameInput} />
            <h1>{this.state.name}</h1>
          </div>
        );
      }
    });

    React.render(<Profile txt="Bunlong VAN" />, document.body);
  </script>
</body>
</html>

State API

Getinitial State
Implement the function getInitialState which returns the initial state of the component. This is an object map of keys to values.

1
2
3
4
5
getInitialState: function() {
  return {
    name: "Bunlong"
  };
}

this.state
To access a component’s state use this.state just like how we use this.props.

this.setState
To update a component’s state, call this.setState with an object map of keys to updated values. Keys that are not provided are not affected.

1
2
3
this.setState({
  name: "Sokleap"
})

When a component’s state changes, render is called with the new state and the UI is updated to the new output. This is the heart of React.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var Counter = React.createClass({
      getInitialState: function() {
        return {count: 0};
      },
      render: function() {
        return (
          <div>
            <h1>{this.state.count}</h1>
            <button type="button" onClick={this.increase}>Increase</button>
          </div>
        );
      },
      increase: function() {
        this.setState({count: this.state.count + 1});
      }
    });
    React.render(<Counter />, document.body);
  </script>
</body>
</html>

So far so good, That’s it!!! See ya!!! :)

ReactJS PropTypes

ReactJS PropTypes

ReactJS is built around the concept of components. The components get many specific attributes just like a HTML tag does.

The attributes are called “props” in ReactJS and can be of any type. It can be a string, function or an Array, as long as its valid javascript you can use it as a prop.

1
2
3
< MyComponent size={24} position="fixed" />
// size & position is props made up by MyComponent component.
// Using anything other than a string you need to wrap your props in {}

What is PropTypes?
PropTypes defines type and which props are required. This benefits the future you using your component in two ways:
1. You can easily open up a component and check which props are required and what type they should be.
2. When things get messed up ReactJS will give you an awesome error message in the console, saying which props is wrong/missing plus the render method that caused the problem.

So how do we write the propTypes?

1
2
3
4
propTypes: {
  size: React.PropTypes.number,
  position: React.PropTypes.string.isRequired
}

And more awesome, if we can’t find a PropType that suits our needs we can write own with regex or shapes:

1
2
3
4
5
6
7
8
9
10
11
propTypes: {
  email: function(props, propName, componentName) {
    if (!/emailRegex/.test(props[email])) {
      return new Error('Give me a real email!');
    }
  },
  user: React.PropTypes.shape({
    name: React.PropTypes.string.isRequired,
    age: React.PropTypes.number
  }).isRequired
}

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>ReactJS PropTypes</title>
    <script src="react.js"></script>
    <script src="JSXTransformer.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      var Profile = React.createClass({
        getDefaultProps: function() {
          return {
            name: 'This is a default prop',
            age: 0,
            activate: true
          }
        },
        propTypes: {
          name: React.PropTypes.string,
          age: React.PropTypes.number.isRequired,
          activate: React.PropTypes.bool.isRequired
        },
        render: function() {
          return(
            <div>
              <h1>Name: {this.props.name}</h1>
              <h1>Age: {this.props.age}</h1>
              <h1>Activate: {this.props.activate}</h1>
            </div>
          );
        }
      });

      React.render(<Profile name="Bunlong" age={0} activate={true} />, document.body);
    </script>
  </body>
</html>

So far so good, That’s it!!! See ya!!! :)

ReactJS JSX

ReactJS JSX

What is JSX?
JSX is a JavaScript syntax extension that looks similar to XML. You can use a simple JSX transform with ReactJS.

It’s more familiar for casual developers such as designers.

XML has the benefit of balanced opening and closing tags. This helps make large trees easier to read than function calls or object literals.

Why JSX?
You don’t have to use JSX with React. You can just use plain JS. However, we recommend using JSX because it is a concise and familiar syntax for defining tree structures with attributes.

How to use?
To start using the JSX library, you need to download a single javascript file from Facebook Starter Kit and include in header tag:

1
<script src="JSXTransformer.js"></script>

The JSX library can also be used directly from the Facebook CDN to increase the performance of the page load by including the link below in header tag:

1
<script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>

Example:

helloworld.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="react.js"></script>
    <script src="JSXTransformer.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      var App = React.createClass({
        render: function() {
          return (<h1>Hello World</h1>);
        }
      });

      React.render(<App />, document.body);
    </script>
  </body>
</html>

Transform
React JSX transforms from an XML-like syntax into native JavaScript. XML elements, attributes and children are transformed into arguments that are passed to React.createElement.

1
2
3
4
5
// Input (JSX):
<App />;

// Output (JS):
React.createElement(App);

So far so good, That’s it!!! See ya!!! :)

ReactJS Getting Start With Hello World

ReactJS Getting Start with Hello World

React is built around the concept of components. This is in contrast to frameworks like Angular and Ember, which use two-way data bindings to update the HTML of the page. In my opinion React is easier to learn than Angular and Ember – it is much smaller and plays nicely with jQuery and other frameworks. It is also extremely fast, because it uses a virtual DOM, and syncs only the changed parts with the underlying page.

How to use?
To start using the ReactJS library, you need to download a single javascript file from Facebook Starter Kit and include in header tag:

1
<script src="react.js"></script>

The ReactJS library can also be used directly from the Facebook CDN to increase the performance of the page load by including the link below in header tag:

1
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react.js"></script>

Hello World
Create a helloworld.html file with the following contents:

helloworld.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="react.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      var App = React.createClass({
        render: function() {
          return React.createElement("h1", null, "Hello World")
        }
      });

      React.render(React.createElement(App), document.body);
    </script>
  </body>
</html>

The primary type in React is the ReactElement. It has four properties: type, props, key and ref. It has no methods and nothing on the prototype. We can create a element through React.createElement.

To render a new tree into the DOM, we create ReactElements and pass them to React.render along with a regular DOM Element.

In codes above we create a h1 element in App component and render it in body DOM.

Hello World - Separate File
Create a helloworld.js file with the following contents:

helloworld.js
1
2
3
4
5
6
7
var App = React.createClass({
  render: function() {
    return React.createElement("h1", null, "Hello World")
  }
});

React.render(React.createElement(App), document.body);

And update HTML file as below:

helloworld.html
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="react.js"></script>
  </head>
  <body>
    <script src="helloworld.js"></script>
  </body>
</html>

So far so good, That’s it!!! See ya!!! :)

ReactJS Concepts and Getting Start

ReactJS Concepts and Getting Start

Well, before we start building anything meaningful, its important that we cover some base concepts first, so lets getting start.

What is React?

React is a UI library developed at Facebook to facilitate the creation of interactive, stateful and reusable UI components. It is used at Facebook in production, and Instagram.com is written in React.

One of it’s unique points is that not only does it perform on the client side, but it can also be rendered server side, and they can work together inter-operably.

Concepts

React has quite a small API. This makes it fun to use, easy to learn, and simple to understand. However, being simple does not mean it’s familiar. There are a few concepts to cover before getting started. Let’s look at each in turn:

React Elements
React elements are JavasScript objects which represent HTML elements. They don’t exist in the browser. They represent browser elements such as an h1, div or section.

JSX
JSX is a technique for creating React elements and components.

Virtual DOM
The Virtual DOM is a JavaScript tree of React elements and components. React render the Virtual DOM to the browser to make the user interface visible. React observes the Virtual DOM for changes and automatically mutates browser DOM to mach the Virtual DOM.

With a small understanding of these concepts we can move to using React. We will build a series of user interfaces, each adding a layer of functionality on the previous. We will build a photo stream similar to instagram.

Rendering
The first order of business is rendering a virtual element (a React element or component). Remember, since a virtual element exists only in JavaScript memory, we must explicitly tell React to render it to the browser DOM.

1
React.render(<img src='http://geekhmer.github.io/logo.png' />, document.body);

The render function accepts two arguments, a virtual element and a real DOM node. React takes the virtual element and inserts it into the given DOM node.

Components
Components are the heart and soul of React. They are custom React elements. They are usually extended with unique functionality and structure.

1
2
3
4
5
6
7
var Photo = React.createClass({
  render: function() {
    return <img src='http://geekhmer.github.io/logo.png' />;
  }
});

React.render(<Photo />, document.body);

The createClass function accepts an object which implements a render function.

The Photo component is constructed and rendered to the document body.

This component does nothing more than the previous React image element but it’s ready to be extended with custom functionality and structure.

Props
Props can be thought of as a component’s options. They are given as arguments to a component and look exactly like HTML attributes.

1
2
3
4
5
6
7
8
9
10
11
12
var Photo = React.createClass({
  render: function() {
    return (
      <div className='photo'>
        <img src={this.props.imageURL} />
        <span>{this.props.caption}</span>
      </div>
    );
  }
});

React.render(<Photo imageURL='http://geekhmer.github.io/logo.png' caption='Phnom Penh, Cambodia' />, document.body);

Specs, Lifecycle & State
The render method is the only required spec for creating a component, but there are serveral lifecycle methods & specs we can use that are mighty helpful when you actually want your component to do anything.

Lifecycle Methods:>
- componentWillMount - Invoked once, on both client & server before rendering occurs.
- componentDidMount - Invoked once, only on the client, after rendering occurs.
- shouldComponentUpdate - Return value determines whether component should update.
- componentWillUnmount - invoked prior to unmounting component.

Specs:
- getInitialState - Return value is the initial value for state.
- getDefaultProps - Sets fallback props values if props are not supplied.
- mixins - An array of objects, used to extend the current component’s functionality.

State
The state object is internal to a component. It holds data which can change over time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var Photo = React.createClass({
  getInitialState: function() {
    return {liked: false};
  },
  toggleLiked: function() {
    this.setState({liked: !this.state.liked});
  },
  render: function() {
    var buttonClass= this.state.liked ? 'active' : '';
    return (
      <div className='photo'>
        <img src={this.props.src} />
        <div className='bar'>
          <button onClick={this.toggleLiked} className={buttonClass}>Heart</button>
          <span>{this.props.caption}</span>
        </div>
      </div>
    );
  }
});

React.render(Photo src='http://geekhmer.github.io/logo.png' caption='Phnom Penh, Cambodia', document.body);

Having state in a component introduces a bit more complexity.

The component has a new function getInitialState. React calls this function when the component is initialised. The returned object is set as the component’s initial state (as the function name implies).

The component has another new function toggleLiked. This function calls setState on the component which toggles the liked value.

Within the component’s render function a variable buttonClass is assigned either ‘active’ or nothing – depending on the liked state.

buttonClass is used as a class name on the React button element. The button also has an onclick event handler set to the toggleLiked function.

Here’s what happens when the component is rendered to the browser DOM:
- When the component’s button is clicked, toggleLiked is called.
- The liked state is changed.
- React re-renders the component to the virtual DOM.
- The new virtual DOm is compared with previous virtual DOM.
- React isolates what has changed and updates the browser DOM.

Composition
Composition means combining smaller components to form a larger whole. For example the Photo component could be used inside a PhotoGallery component.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var Photo = React.createClass({
  toggleLiked: function() {
    this.setState({liked: !this.state.liked});
  },
  getInitialState: function() {
    return {liked: false}
  },
  render: function() {
    var buttonClass=this.state.liked ? 'active' : '';
    return (
      <div className='photo'>
        <img src={this.props.src} />
        <div className='bar'>
          <button onClick={this.toggleLiked} className={buttonClass}>Heart</button>
          <span>{this.props.caption}</span>
        </div>
      </div>
    );
  }
});

var PhotoGallery = React.createClass({
  getDataFromServer: function() {
    return [
      {
        url: 'http://geekhmer.github.io/phnom_penh.png',
        caption: 'Phnom Penh'
      },
      {
        url: 'http://geekhmer.github.io/sr.png',
        caption: 'SR'
      }
    ];
  },
  render: function() {
    var data=this.getDataFromServer();

    var photos = data.map(function(photo) {
      return <Photo src={photo.url} caption={photo.caption} />
    });

    return (
      <div className='photo-gallery'>
        {photos}
      </div>
    );
  }
});

React.render(<PhotoGallery />, document.body);

The Photo component is exactly the same as before.

There’s a new PhotoGallery component which generates Photo components. In this case there’s some fake server data which return an array of 2 objects, each with a url and caption.

The data is looped over and will generates 2 Photo components which are inserted into the return value of the component’s render function.

Events
React also has a built in cross browser events system. The events are attached as properties of components and can trigger methods. Lets make our count increment below using events:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Counter = React.createClass({
  incrementCount: function() {
    this.setSate({count: this.state.count + 1});
  },
  render: function() {
    return (
      <div class="my-component">
        <h1>Count: {this.state.count}</h1>
        <button type="button" onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
});

React.render(<Counter />, document.body);

React events:
- Clipboard Events - onCopy onCut onPaste
- Keyboard Events - onKeyDown onKeyPress onKeyUp
- Focus Events - onFocus onBlur
- Mouse Events - onClick onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseOut onMouseOver onMouseUp
- Touch events - onTouchCancel onTouchEnd onTouchMove onTouchStart
- UI Events - onScroll onWheel
- Form Events - onChange onInput onSubmit

So far so good, That’s it!!! See ya!!! :)

Why You Should Use ReactJS for Your Next Project?

Why you should use ReactJS for your next project?

React, developed by Facebook, is an open source library for building User Interfaces. As the front end world moves too fast. I am a big fan of AngularJS and a few months back I started trying React. The biggest reason for me to try React was to create apps that render on both client and server (with a little help from other libraries as well). In this article I am going to share the best reasons to use React in your next project:

1. Can Render on Both Client and Server
Well, React uses a concept called Virtual DOM (discussed subsequently) that gives your UI a great performance boost. You can build the UI using React and render it on both server and client. This has a strong advantage over traditional SPAs (Single Page Apps). While SPAs are great for building rich AJAX based web apps. SEO is the biggest challenge. With React what you can do is take a hybrid approach and create apps. The initial request to your app should be a server side rendered version. The subsequent user interactions should use client side rendering. With this approach your app takes advantage of all the features of SPAs while still being search engine friendly. You don’t need the techniques to pre-render your pages anymore.

2. Component Oriented Development is Good
React takes a component oriented approach. You can break your whole UI in terms of reusable components. As the components are well encapsulated, reusing and testing.

3. Separation of Concerns
By expressing your UI in terms of well encapsulated and reusable components you achieve separation of concerns. A component shouldn’t try to do more than one thing. Rather it should do only one job and anytime you need to separate the concerns you build new components.

4. Simple and Declarative
Your components represent how your app looks at any given time. Simply feed some data to your components and React takes care of refreshing the components when the underlying data changes.

5. Virtual DOM is Fast
React creates a fake DOM for you. Most of the times you will be working with this virtual DOM as it’s way faster than manipulating the actual DOM. React keeps an in memory copy of the DOM and your components describe how the DOM looks at any given time. So, React is fast in computing the Diff and knows which parts to update. In short React decides what’s the fastest way to update the UI and this technique is definitely performant.

6. JSX is Cool and Simple
JSX is known as JavaScript XML transform. You create your components with JSX which are then compiled into JavaScript. Don’t worry! React provides tools which continuously watch your source directory and re build whenever there is a code change. JSX, on the other hand, has 2 simple benefits such as:
- It’s easier to visualize the DOM with JSX syntax.
- Designers can be very comfortable with JSX.

7. Reactive Updates
React’s philosophy is based on Reactive Updates. Traditionally what we do is watch the data and update our UI whenever the data changes. On the other hand React components have a render method which describes how the DOM should look like at any point. React caches the value obtained from the last call to render and compares it each time render is re-run. So, it knows exactly which part of your component needs to be updated and refreshes the UI accordingly.

8. Event Handling Done Right
React takes care to bubble and capture events according to W3C spec. It uses a synthetic event system to ensure all the events work consistently across the browsers IE 8+. So, you should not be afraid of the inconsistent DOM APIs anymore.

9. React Addons
React Addons offer additional utilities that can help you write better UIs. For example, you can use the Animation and Two way data binding Addons. You can also use the testing addon to test React components using test framework of your choice.

10. Facebook has Created Something Awesome
React is being used in large websites such as Facebook, Instagram, The New York Times and many others. Clearly, React is doing a great job.

So far so good, That’s it!!! See ya!!! :)

10 Tips to Speed Up Rails on the Front

10 Tips to Speed Up Rails on the Front

Is your Rails website performing poorly? Are clients and users complaining about 5-10 second pageloads, timeouts on mobile devices, or images that take forever to display? In some cases the solution lies on the backend — caching requests, speeding up DB queries, etc — but often, there are front-end optimizations you can look at first, that could have a huge effect on how fast a site feels.

Evaluating front-end Performance

Check out www.webpagetest.org. For a quick glance at your site, look at the grades in the top right for immediate problems, and also check the two “Speed Index” measurements for first and repeat views. Since webpagetest saves all your tests, you can re-run after making some changes to easily see what’s improved.

Avoiding Premature Optimization

Performance optimization takes time and resources, both of which are often in short supply. It’s hard to find the point where optimizations start to cost more than they save, and every site and team have their own unique challenges. I’ve ordered the notes in this post in order of payoff: if you want to start optimizing but don’t know where to begin, the first few ideas on this list will probably give you the biggest bang for you buck.

GZIP

The biggest, easiest performance you can implement is gzipping HTML/JSON/JS/CSS/font file responses. It can drastically reduce the size of transferred files, but it’s easy to forget and isn’t in most default configs.
- Using Rack:Deflater
- Using nginx config
- Gzipping font files

keep-alive

keep-alive is another easy win that speeds up asset delivery by reusing the existing connection between client and server. Turning it on should be a no-brainer.

Optimize user-uploaded Images

You generally want to convert all uploaded images to JPGs, strip metadata, and optimize them as much as you can without heavy quality loss. Without this step, an admin or user can easily tank the pagesize by uploading a 24-bit PNG or similarly uncompressed image. I recommend Dragonfly for on-the-fly image optimization — it lets front-end developers and designers fiddle with image details without needing to go back and update all your existing images on production after the change.

Caching and CDNs

Cache expiration
Set all assets (JS, CSS, images, fonts) to expire in a year, using either far-future expires or max-age Cache-Control headers. There are a lot of simple instructions available for setting this on the asset pipeline and for CDN assets.

Fingerprinting
If you set far-future caching, you need unique, fingerprinted filenames. The asset pipeline’s precompile command will already handle this, but in most cases it won’t happen automatically for user-uploaded assets. For example, if a user edits their avatar image locally and re-uploads it to the server with the same name, and you’re serving it with far-future expires headers, you’ll have a problem. If you’re uploading files with something like Carrierwave or Paperclip, make sure you’re taking this step.

CDN
Migrating user-uploaded images and Rails assets to a CDN can improve download time by moving asset servers “closer” to the user. Both caching and fingerprinting rules still apply to CDNs.

SPDY

SPDY is a networking protocol that can speed up page performance considerably, especially on pages with a lot of assets (example). It’s available in the majority of browsers and ready for production use. It requires that you set up SSL, which is admittedly a hassle, but it isn’t much work beyond that.

Inlining assets

(Note: If you’re using SPDY, it’s recommended that you DON’T inline your assets — see SPDY best practices. Thanks Robert Fletcher!)

JS
As a general rule, loading JS in the head is a bad idea — you want to move it to the bottom of the body. However, in some cases moving it isn’t possible. If a design relies on Modernizr to add classes to the body as early as possible to create a consistent visual experience, Modernizr needs to remain in the head. In this case, try inlining the JS in a script tag instead of creating an extra, blocking request. This technique trades a faster initial pageload for slower subsequent pageloads (since subsequent loads will no longer load the file from browser cache). In a lot of cases the other pageloads are just barely slower, and it’s a good tradeoff.

CSS
As a site grows, it becomes unreasonable to bundle all styles into a single application.css file. Users can end up viewing pages that load 100% of a site’s styles but only use 5-10%. In cases like this, you can break up page-specific styles into individual files and load them with a scheme that uses the controller/action to find CSS files.

Taking it further, there’s a good chance that if your view-specific CSS is small and users aren’t visiting many instances of the same view, making them request a second stylesheet isn’t necessary — just like with JS, you can inline them onto the page. Check out this gist for the setup I’ve used to inline CSS and JS assets in the past.

Images
If you have pretty small images or single unique images on a view, it could be worthwhile to inline them as base64 strings instead of sending them as separate requests, using Ruby’s Base64 module. (Warning: in IE8, your base64-encoded images need to be 32kb or smaller, or they simply won’t display.)

jQuery and UJS

Rails ships with jQuery 1.9.x and jquery-ujs built into application.js, but jQuery is a pretty big library, and presents some optimization opportunities:
- Switch to jQuery 2.x — it’s smaller, but means dropping support for IE8. You could also use browser conditionals to load 1.9 for IE8 and below and 2.x for above, but you still want to combine jQuery into a single file with your other scripts, so you might end up with something like application-oldjquery.js and application.js.
- Cut UJS, or cut them both — if you’re not using any UJS features, you can remove it, which might make jQuery an unnecessary dependency.

At the time of this writing there’s no jQuery-less alternative for UJS, but it sounds like the team has considered the idea.

Pagespeed

Google’s pagespeed module gives you a number of tools that can speed up front-end performance by making minor tweaks (trimming the domain out of local URLs, inserting DNS prefetch tags, collapsing whitespace) or major ones (lazy-loading images). I encourage you to install it and investigate some of the filters. Each filter has documented “Risks” that are worth reading before you implement — some of them, like remove quotes are low-risk filters that you could probably implement today with no downside.

So far so good, That’s it!!! See ya!!! :)

Open Sourcing a Gem

Open Sourcing a Gem

Considerations when Open Sourcing
When open sourcing a gem (or any project, this post can be generalized to not just focus on gems), there are a number of things to consider. The first check is to ensure that the use case is general enough that it is likely to be helpful to other parties. Though the project might never gain many external users, it is a good sanity check before taking on the work to open source the project. Following this there are a number of things to think out, with the purpose of determining a track of work that needs to be taken (if any) before the gem can be open sourced.

Generalize the implementation
- Remove coupled business logic and application specific code.
- Ensure no keys/account information were stored in the repo (even in past commits). Typically not considered a good practice, but it is something to be aware of when releasing the source of a project publicly.

Set bounds on the responsibilities
- What is the purpose of this gem and what needs is it fulfilling?
- Take a step back from how you currently use the library. What other potential use cases might others use it for? Is it worth generalizing the implementation to aid these other use cases?
- Set bounds on the responsibilities that the gem will take care of.
- What will the gem provide and what is left up to the user? In the case of Signalman, we allow users to customize the URL of the Signalman admin page, but it is up to the user to provide additional authentication besides obscurity. Signalman is a gem designed to aid with A/B testing, not authentication.
- Try to stick to the gem’s core competencies. Do not add features at a whim to quell user requests. This can cause a gem to grow out of control and become hard to manage or even discern its original purpose/intent.

Consider strategies to manage repository ownership
- Like it or not, becoming a maintainer is a big responsibility. If you are open sourcing a project with a team, this will greatly ease the burden, but you must still consider processes to manage external pull requests and issues that arise.
- Giving the user power and encouraging pull requests and a community that supports each other’s issues can also relieve the burden of being a project maintainer. You can help this process by adding documentation for contributing and making it easy for other parties to contribute to the project. This also means providing help to newer developers; you never know who might become a leading contributor in the future.