Blogging Best Practices: Categories v Tags

Categories and tags can be a very useful tool to help make a blog/website more navigable for users and boost SEO to boot. However the specific execution of these features are very much a matter of personal taste and discussion of the subject quickly leads to confusion. This is even more the case for a blogging platform such as Jekyll, which has both few plugins to automate the process and best practices. I myself am guilty of blindly using the very straightforward YAML declarations that Jekyll supports without any real forethought. Wordpress however provides very explicit documentation on the subject, which we can use as a good starting place.

Very simply, categories describe the gross structure of your blog, tags label specific entries. By analogy consider a publication, categories would be the table of contents, tags would be index headings. With this in mind we can anticipate that there will always be at least as many tags than categories, most likely more. The exact number depending on the breadth and depth of topics you choose to blog about, and the level of specificity each category contains. Generally speaking, tags describe something about a particular post, categories group several posts together. Once you have come to a decision how you will use categories and tags in your blog, consistency is key to make the most of your conventions. Another point to bear in mind, more specific to tags, is to make sure to use them effectively. Tags can be both underused and overused, ideally - I use the term very loosely here - you want each tag to be used more than just a few times, without being used for any and every post. Another way to think about this is whether or not the tags actually inform or help users. Analytics services could be helpful here to indicate user flow through your blog.

In practice, the first step is to think ahead: anticipate the breadth and depth you could possibly write about. Although this might not be entirely realistic, it will help prevent the problem of tagitis in the future. Beyond this, you may wish to think about how a user may navigate using categories or tags. As mentioned above, Jekyll tends to have a fairly sparse set of plugins, though there are some authors who have looked at this specific issue.

All the best,

Tom

jQuery Tips

This is a very short post on some useful tidbits I’ve learnt using the ubiquitous jQuery library. I have occasionally found myself in a sticky situation because either (a) the library had not loaded, (b) I’ve been using the wrong version.

We can check if the library is available to us by using either a bang (or two), or using the instanceofoperator. We can use jQuery and $ interchangeably, as they are aliases.

// Load library if it hasn't already
if (!window.jQuery) { 
  // code goes here ...
}

if (typeof window.jQuery == 'undefined') {
  // 'ere be code ... 
}

In the previous example we used window.jQuery as this will simply result in a truthy output. Using just jQuery or $ alone with the leading bang will lead to a reference error.

We can get the version number by logging one of the following,

// Either ...
jQuery.fn.jquery // or jQuery().jquery

// or equivalently
$.fn.jquery // or $().jquery

Of course, we would need to know the library had already loaded before checking the version!

Short and sweet!

All the best,

Tom

High Performance CSS

CSS performance covers a wide range of topics. We can mean anything from selector performance, property performance, architecture practices, and file size to mention a few. At times all these considerations pull in different directions, as what is most efficient for browser processing is least efficient for the developer’s time. This is especially true in relation to selector performance as the most efficiently rendered selectors, ids, are least practical for the purpose of CSS architecture. For the purpose of this post, I’m going to ignore the issue of selector performance as it quite difficult to predict performance costs ahead of time, can lead to bad practices (as already mentioned), and is highly browser dependent. (That said, there is a point to writing well structured selectors, but generally speaking this will be the place where good architectural practices step in.)

We instead want to explicitly look at the overall stylesheet size and property performance to achieve consistent, reliable, and meaningful performance gains for our stylesheets. In relation to the former, it is probably no surprise that a smaller overall file size performs better simply as there are fewer bytes to send over the intertubes. However the gains in rendering time can be significant to say the least. Sticking to a consistent CSS architecture style is the first step to creating smaller stylesheets. Further down the line, we may need to prune unused styles to reduce file size.

Property performance is not often discussed but if neglected can cause real performance problems. Costly properties are those that slow down the render tree construction most. These are properties that require the browser to perform more manipulations, repaint or reflow, in order to paint to/reorganise elements on the screen e.g. a background colour with a gradient as opposed to a plain background. For a WebKit based browser, “border-radius” and “transform” have been shown to be some of the most expensive properties. Our overall design should be sparing with browser reflows and repaints.

The main take away: solid CSS architecture is the gift that keeps on giving, it will empower developers to maintain a DRY, semantic stylesheet, which ultimately leads to performance gains come rendering time. This topic also touches on the issue of Critical Rendering Path optimisation, which I will cover in the future.

All the best,

Tom

CSS Attribute Selectors

We very often style our markup using attribute selectors such as class name or ID. However, CSS gives us a great deal more sophistication when it comes to using CSS attribute selectors.

To start with, we have a vanilla attribute selector,

[attr]

which will match any element with matching attribute selector. If instead we wanted to select a tag with a particular attribute,

elem[attr]

Easy enough. A more subtle point: It will probably be best to assume any attribute selector value i.e. attr=”value”, is case sensitive to avoid any nastiness.

Now the fun part! We can prepend the equals sign between the attribute name and attribute value to define the relationship between them.

[attr='value']

Matches all elements with “attr” with value exactly equal to “value”

[attr~='value']

Matches all elements with “attr” with value containing “value” within a space separated list e.g. rel="this is my value"

[attr|='value']

Matches all elements with “attr” with value containing “value” within a dash separated list e.g. rel="this-is-my-value"

[attr^='value']

Matches all elements with “attr”, with value starting with “value”

[attr$='value']

Matches all elements with “attr”, with value ending with “value”

[attr*='value']

Matches all elements with “attr”, with value contains at least one instance of “value”

You can go even further and combine the rules given above to create multiple attribute selectors.

Altogether, CSS attribute selectors provide more fine-grained control to style markup. For example, you can choose to style anchor tags that link to external pages differently - no need to needlessly suffer classitis.

All the best,

Tom

JavaScript Design Patterns: Revealing Module Pattern

This post carries on from yesterday’s so if you haven’t read, get to it! As you may have guessed from the name, the revealing module pattern is a variant of the module pattern already covered. However, it has proven so popular as to warrant specific mention in most to every discussion of design patterns.

The two takeaways from the module pattern were,

  1. We can choose the visibility of our variables and methods, either public or private,
  2. We use object literal notation to set out public variables and methods.

This is reasonably effective though a bit crude: We have the rather unfortunate practice of writing private entities differently to public ones, the latter use object literal notation. Furthermore it can lead to needless repetition in our code if we wish to reference public entities from another. The revealing module pattern leads to much cleaner code as all our methods and variables, regardless of visibility, are written together. We then return - reveal - the entities we wish to make public. For instance,

var House = (function () {
 
  // Both public and private entities go here using the same syntax
  var privateVar = 0;
  var publicVar = true;
  
  function privateMethod() {
    console.log(privateVar);
  }

  function publicMethod() {
    privateVar++;
  }
 
  return {
 
    // Public properties and methods go here.
    // The methods above are scoped to the closure, this gives us the
    // added benefit of sticking to a more specific naming convention.
    garage: publicVar,
    goShopping: publicMethod
 
  }
})();

Altogether, a bit nicer to look at. There may be some concerns, as with the vanilla module pattern, regarding the difficulty of testing or patching methods which refer to private entities.

All the best,

Tom

JavaScript Design Patterns: Module Pattern

Similar to my previous posts in this series, the module pattern is perhaps better described as a general best-practice than as by a distinct structure. Unsurprisingly then, there are a number of common variations in the wild such as using import mixins and exports. At its core it rests on a very simple principle we will see a lot more of in the future: Using object literal notation to assign property values and method to our class-like objects. This can be particularly useful as a (rather crude) way of setting properties as either public or private. An example using the IIFE pattern,

var House = (function () {
 
  // Private properties and methods go here,
  // everything here is scoped to the function closure
  var numToiletries, printToiletries;
 
  numToiletries = 0;
 
  printToiletries = function( numToiletries ) {
      console.log( numToiletries );
  };
 
  return {
 
    // Public properties and methods go here
    garage: true,
 
    // We can still interact with private variables here
    goShopping: function() {
 
      numToiletries++;
 
    }
  };
})();

This allows us to namespace private variables to the closure. However, this particular pattern can lead to some challenges if we wish to change the visibility or a particular variable at a later date: We will have to make a change at each place the variable was used. This frustration inspired the more sophisticated revealing module pattern, which I’ll cover tomorrow.

All the best,

Tom

JavaScript Design Patterns: Singleton Pattern

The singleton pattern is perhaps one of the more controversial patterns in common use. Ironically, both its proponents and detractors will point to the same feature of the pattern as its main plus/minus. This pattern provides a single instance of a class (or JavaScript object), with a global point of access: it advocates global namespace pollution. This can be particularly useful when using third-party libraries. Although there may be coping strategies available, jQuery for instance provides us with $.noConflict(), it is generally a sign of bad design. Code structured as a singleton pattern indicates that our logical is tightly coupled, which can make debugging nightmarishly difficult.

Unlike the other patterns we will come across, the singleton pattern is not defined so much by a specific written structure, we could just as well talk about either object literals and function closures. All we want is something that provides a globally available object instance. Carrying on from my previous post on the constructor pattern, we can create a singleton example, shamelessly hoisted from Rob Dobson’s post on the subject,

function House() {  
    // check global scope for existing object
    if (typeof House.instance === 'object') {
        return House.instance;
    }

    // bog-standard constructor
    this.bedrooms = 3;
    this.bathrooms = 1;
    this.garage = true;

    // cache this particular object instance
    House.instance = this;

    // implicit return
    return this;
}

This is admittedly quite crude, and highlights the key issue with globally available variables: we have no particular control where and how a given House instance is set. Although not specific to the singleton pattern, we can make it far more sophisticated by making use the IIFE pattern to make the contents private.

All the best,

Tom

JavaScript Design Patterns: Constructor Pattern

The constructor pattern is arguably the bread and butter design pattern. Some context: JavaScript is a so-called classless, inheritance is instead prototypal: objects inherit from objects. This particular feature of the language was originally inspired by Self. With this in mind, we try to mimic class-like inheritance using objects - in particular we want to create object constructors.

To start, all we need to bear in mind is some basic JavaScript syntax,

  1. We can append key to objects using the “dot” syntax,
  2. We create a new object instance using the new keyword.
1. Object.key = value;
2. var object = new Constructor( /* arguments */ );

The pattern usually follows,

  1. Use a function closure to create an object-like structure, this is our “constructor function,”
  2. Append variable values to an object instance using the this keyword,
  3. Append shared object methods to the Prototype object.

Altogether we would get something,

function House( bedrooms, bathrooms, garage ) {
  // this should prevent some annoying problems 
  // such as calling the constructor without `new`.
 "use strict";

  this.bedrooms = bedrooms;
  this.bathrooms = bathrooms;
  this.garage = garage;
 
}

// In other words we want House.prototype.hasOwnProperty('hasParking') === true
House.prototype.hasParking = function () {
  return "Has parking space:" + this.garage;
};
 
var bungalow = new House( 2, 1, true );
var terrace = new House( 3, 2, false );

Though simple in its execution, depending on the nature of the problem at hand the constructor pattern could lead to a lot of unnecessary bloat. In the coming weeks, we will see constructors again and again in some form or another, as they often form a smaller part of more elaborate patterns.

All the best,

Tom

JavaScript Design Patterns: Introduction

In this post I want to cover the general what and why of design patterns. Design patterns are popular, well-supported recipes for writing code. Sticking to a design pattern, as opposed to going completely freestyle can have a number of benefits. Arguably the most important advantage to using a design pattern is the larger community support that they engender: These patterns stick to a known structure, which is more readily communicated, and tend to follow best-practices. Furthermore, the structure they provide often helps prevent making costly mistakes with consequences further down the line. This can be contrasted with so-called “anti-patterns”, which true to their name go against the main advantages of following a design pattern. This includes such sins as namespace pollution, using less efficient non-native methods, and inline script.

Although there is always a kind of specificity in any code, after all we want solutions not just good practices, there are a few commonalities when it comes to writing a true design pattern. These include:

  • The practicality of the solution,
  • How well it follows best practices,
  • How easily a newcomer can come to grips with the pattern.

The latter point naturally leads to a strong emphasis on good documentation and community support, which is something of a virtuous circle. In other words, a design pattern is only a pattern in so far as it follows a solid set of principles.

I hope to work my way through a high-level overview of some of the more popular design patterns in the coming months.

All the best,

Tom

Maintaining Reusable Stylesheets: Overview of SMACSS

Created by Jonathan Snook, SMACSS, or Scalable and Modular Architecture for CSS, is one of a handful of working practices to promote the writing of consistent, maintainable, and understandable CSS. There might be further considerations to push towards more efficient code, however as the savings in processor time are minimal it is probably best to neglect this metric in favour of saving programmer time. SMACSS is distinguished from its competitors such as OOCSS and BEM, by its emphasis on using selector names which fall into categories determined by their type and function. Sticking to vanilla CSS, SMACSS starts from the principle of sticking to class selectors as much as possible to prescribing rules relating to, naming conventions, state changes, selector depth, and modularity.

Sticking to Classes

We want to stick to using classes, and classes only. Classes are reusable, which is good for modularity and future-proofing, and as for styling purposes ids give us no added benefits in terms selector performance. Although this practice places an absolute premium on our naming convention, provided we are consistent and plan ahead, using classes alone should not put us at any disadvantage.

Naming Conventions

SMACSS splits CSS selectors into five different categories: base, layout, module, state, and theme. This is our first line of defence in maintaining a DRY stylesheet, the categories relate as follows,

  • Base rules are defaults, usually provided by something like normalize.css. These are an exception to the rule above, as they usually apply to element tag selectors.
  • Layout rules are the containers for our module rules, these relate to the spatial divisions within our page. The class selectors for these rules follow the pattern l-<name> e.g. l-fixed.
  • Module rules are the mainstay of our stylesheet. These are highly reusable parts of stylesheet, we put anything we want shared across multiple distinct elements here. There isn’t such a straightforward naming convention to follow due to the frequency of use, however we do want to stick to semantically meaningful, generic, and reusable class names.
  • State rules determine styling for state changes such as user interactions, selector names follow the pattern is-<state-name> e.g. is-active.
  • Theme rules can add an additional layer of styling for customisation or typography.

To elaborate a bit on terming selectors “semantically meaningful”, class names should indicate how selectors relate to content on the page, and how they relate to one another. For instance indicating parent-child nesting by a shared prefix, we will cover this in more detail below. This practice both rules out using element selectors in general - although HTML5 gives us some help here - and more broadly, ensures that our class names clues us onto the function of a given selector.

State Changes

Naming state style rules is one thing, but applying them usefully is quite another. SMACSS doesn’t so much prescribe a particular way of rendering state changes so much as putting an emphasise on using the most appropriate way of handling the state change in question in keeping with our considerations for modularity etc. For instance, if we were to represent a state change using class names we would want to ensure the code is not heavily dependent on the DOM structure: rather than target a parent container with our CSS selectors stick with a sibling selector instead.

Selector Depth

The aim of the game is to go for as shallow a depth with as few selectors as possible. Taken together, this looks to make the styling as modular as possible: it will ultimately be very generic and be less dependent on the DOM structure.

A good practice is to avoid duplication, for instance the following,

  .classy-name div, .equally-classy-name div {
    /* funky styles */
  }

should be a cue to introduce a joint class name to target both elements.

The added benefit of using few selectors is that we needn’t make use of ids or !important overrides unless absolutely necessary. We would simply add in another class name to get the desired styling to render, this is important when considering sub-modules below.

Modularity

We’ve pretty much touched on modularity throughout, which is not particularly surprising considering its importance in SMACSS (it’s in the name!). However, we have not discussed sub-modules: when needs be, we might want to distinguish a particular module based on its location or use within the page e.g. a sidebar as opposed to a pop-up, with a common parent class selector. As before we want to keep our code as generic as possible. To do so we would use an additional class selector with a name that reflects its parent container, perhaps by using a shared prefix.

Wrapping Up

Admittedly there is very much more to cover, such as how to make the most of preprocessors using SMACSS and some other formatting considerations. Thankfully there is very much more information on the topic, not least the official website and book. I myself am very new to the practice, and am sure to return to the topic in the future.

As always, all the best,

Tom