There are rafts of great posts and practical information available on the Internet about how websites should be built and the code that powers them should be written. So much so, that at times, especially if you are just starting out, it can seem like swimming through treacle just trying to keep up. With this in mind, here’s what I have found worthwhile spending time on with front-end code. So I’m going to go broadly over front-end code/stuff (HTML, media, CSS and JavaScript) and consider what techniques and practices I personally feel are worth the time understanding and implementing and why.

I’m going to give everything that follows the great big caveat that as with everything relating to website development, “it depends”. I’m giving my own biased view of what matters but that may not necessarily be applicable for your own scenario.

The sites and projects I work with week in and week out are not the Facebook’s and Twitter’s of this world. Almost without exception they have budgets of 10K or less. They are projects where time and budget are limiting factors and this effects which squeaky wheel gets the oil. So with that in mind…

Images

Optimising images

First and foremost, if you want to provide the best experience for all users of your website don’t just compress your images (using Fireworks or Photoshop and choosing the most appropriate format and setting such as PNG/JPG/GIF) but also optimise them. There’s lots of surplus information in images (meta data and the like), even those that are compressed. Removing this information through optimisation doesn’t degrade the visual quality of the image and yet doing this on just one image can easily save more file size (which affects page loading speed in a REAL tangible way) than removing a JavaScript library, plugin or a whole file of CSS.

Tools that can optimise images:
CodeKit (OSX)
EWWW Image Optimizer (WordPress plugin – might require the help of your host to install)
Image Optimizer (Windows – Visual Studio extension)
Kraken (Online tool also available as a browser extension)

Verdict: Do it, it’s easy to do and makes significant differences to page speed. Whatever device you view the page on; everyone benefits.

Serving images at the appropriate file sizes

Using an image appropriate for the size it will be displayed at in the browser presents a pickle at present. You know what I mean:

This used to be easy with fixed width designs – you knew the space the image would fill so could export an image to match.

For example, say you have a DIV that displays on screen at 800px wide. You would export an image to fill that gap that was 800px x 400px:


an image

You wouldn’t want to export an image at 1600px x 800px to fill this space as this would be a complete waste of file size. However, with responsive designs things are far more complicated and this kind of situation is sometimes unavoidable.

Generally, although no-one is particularly happy with the hit, we export the image at the largest size we envision it will be viewed at, link to that image as normal but leave off the width and height attributes. By using a snippet of CSS (max-size: 100%;) the image scales to the available space:


an image

However this is far from ideal. What about users on smaller screen devices? They are downloading an image sometimes 3–4 times larger than their device can see with the associated bandwidth hit that entails.

It’s a well documented issue and there are a few techniques on the table to deal with it (such as Matt Wilcox’s Adaptive Images and the picturefill polyfill). For now however, if for example the maximum size the image will fill is 800px wide, I tend to export an image 850–900px wide. This gives me a little lee-way in case of design amendments (say the client asks for the design to be a little wider). It’s not an ideal situation but I’m also not entirely happy with any of the other offers on the table at present.

It’s definitely worth opting for a mobile-first implementation if possible (in this instance you would use the smallest version of a file first and then swap in larger versions for larger viewports with either JavaScript (e.g. Polyfill) or a combination of PHP and JavaScript (e.g. Adaptive Images). There’s more on these two techniques in this post.

Verdict: If you are building a fixed width design ensure you only use images that are the size of the space they display in. If you are building a responsive design, where possible, use a ‘mobile first’ technique and swap in alternate images for larger viewports. With a responsive design, implementing a ‘mobile first’ technique on images could possibly save far more bandwidth than all the other economies you are likely to make elsewhere (such as concatenating and compressing JS/CSS).

SVG (and fall backs)

Where possible, provide SVG versions of logos and icons. SVG (Scalable Vector Graphics) are a fraction of the size of a normal bitmap image. The downside is that support for SVG graphics in browsers is limited (IE8 and below and Android 2–2.3 are notable absentees) and the tools for exporting to SVG are few and far between (of the programs I own, only Illustrator exports to SVG with any degree of finesse).

Vector Vs Bitmap
A vector based image can scale to any size/resolution as it is defined as a set of mathematical values. A bitmap on the other hand is ‘fixed’ as a series of ‘dots’ in set positions. As such, bitmap images (JPG/GIF) are far more wasteful and don’t scale well. However, as photos are bitmap they are completely unavoidable in many instances.

Verdict: If you don’t need to support IE6/IE7/IE8 or Android 2.0–2.3 any images that can be SVG should be. Make sure you test in as many devices as even my limited experience with SVG images has shown that implementation can be flakey. If you do need to support IE8 you can always fork your code with Modernizr. This will let you serve an SVG file for browsers that can use it and a PNG for those that don’t. There’s more on using Modernizr in this post.

Icon Fonts instead of images

I’m a huge fan of icon fonts as you can probably tell if you look about this website. Like SVG graphics they provide a scalable way of providing images (they can be any size, any colour and enjoy text shadows, webkit-gradients & box-shadows – all configurable through CSS alone). With an icon font, each icon becomes a font glyph, so a number of icons can be a single font file. This provides the ability to remove large numbers of images from a site and replace them with a single asset (a web font). Again, this post provides more information on how to actually use icon fonts.

In certain cases they, along with normal web-fonts, can have problems (Opera Mobile being a prime example). I also often find with IE8 for example that the first load of the page doesn’t render the web-font (a refresh sorts it but that isn’t ideal). But for my money, any trade-offs are worth it.

Great icon fonts
Pictos
IcoMoon

Verdict: Where possible use an icon font. The tools for implementing them are easier than ever (here’s a screencast I did on how to make a custom Icon Font) and once you’ve used them, I think it’s hard to go back. They work across most devices and browsing platforms an offer great economies compared with separate images or an image sprite. However, where UI elements are essential, and vast and wide browser support is a necessity, tread carefully.

CSS

Compressing CSS

First and foremost: COMPRESS YOUR CSS. When you have finished working on a site, ensure you compress the CSS before upload. I believe this is the single biggest gain you can make with CSS. It can easily reduce the file size by half. Pre-processors like Sass can do this for you on compile (where they take the pre-processed Sass/LESS file and convert it into plain CSS).

If you don’t use a pre-processor (I aim to change that) ensure you have some other means of compressing the CSS. Applications like CodeKit and any decent code editor such as Sublime Text, Coda, TextMate etc have plugins to do this. Worst case, use an online tool like CSS Compressor online.

As a simple illustration. The CSS for this site, at the time of writing is 59KB uncompressed (that includes comments in the file and the like). The compressed version is 34KB: nearly half the size.

Verdict: This is worth it – easy to do, decent gain.

Gzipping

If you want to send a large file to someone you’ll zip it up. This is just what all decent servers do too. They gzip assets like CSS and JavaScript which the browser then deflates on receipt. Make sure the server you are using supports gzip and that you are delivering anything you can that way. It isn’t something you actually do front-end (e.g. you don’t manually gzip the files and upload them – the server handles it) but it should be something you ensure is happening. Like many of these optimisations, Google Page Speed and Yslow will give you recommendations for the page and advise if you aren’t serving things Gzipped.

Verdict: This matters. As an example, the CSS file noted above that started at 59K and then got compressed to 34KB ends up around 7KB when gzipped – a huge economy!

Should you use ID or classes?

It’s a fact that using an ID to target something in CSS is faster (more ‘performant’) than using a class. For example:

#container { }

Will be faster for a browser to target and paint the enclosed styles onto the page than this:

.container { }

However, that difference is in Milliseconds – ultimately not something you want/need to worry about. So why do people rage and debate about whether you should use an ID or a class name to target styles?

I believe a key reason stems from when Nicole Sullivan started talking about Object Orientated Cascading Style Sheets (OOCSS). One of the prime motivations of this way of thinking is to abstract CSS rules where possible. What does this mean? Well, at the risk of butchering her good work (and I really encourage you to go check out her slides and info) and paraphrasing her aims, it means don’t ‘lock’ styles to a particular element. Where possible pull them out so they can be re-usable. For example, lets say we have a confirmation button at the end of a form:



We could style it like this:


#input {
  border: 1px solid #000;
  color: white;
  background-color: red;
  padding: 1em;
}

However, because we have added these styles to an ID, we can’t use them anywhere other than on an element with an ID of ‘input’. As you can only have a single unique ID on every page that’s a little limiting.

Instead, if we added the styles to the class:


.input {
  border: 1px solid #000;
  color: white;
  background-color: red;
  padding: 1em;
}

We could add the class of input to any other element in the HTML to get the same styles applied. There’s nothing OOCSS about this so far. However, you would then take this a level further and look at what is different from element to element. For example, you might want to create an umbrella ‘box’ style and then add additional styles for different types of boxes:


.box {
  padding: 2em;
  background-color: #f2f2f2;
  color: #999999;
}
.warning-box {
  border: 2px dotted #ff0b13;
}
.success-box {
  border: 2px dotted #11c909;
}
.info-box {
  border: 2px dotted #091fff;
}

Then for a specific box you would add two HTML classes. One for the basic styles and then the extension (the particulars). For example:



How and what you choose to abstract into different classes is up for debate. It’s quite common to separate style from position for example but it’s perhaps easiest to thing in terms of patterns. Where a noticeable design pattern is repeated more than one it’s probably a good candidate for abstracting in an OOCSS style.

That’s the general idea. Abstracting styles and re-using them where possible – hope that hasn’t done her work a disservice with that whistle-stop overview. Read more about OOCSS at Nicole Sullivan’s site and at the OOCSS repository on GitHub.

Now back to IDs. Ultimately, you may not have control about where you have a class or ID selector in the markup. I certainly don’t lose any sleep about using ID’s to style some elements. But it is important to know the effects of doing so (they are VASTLY more specific than classes so slapping them on any old thing is a high rode to maintainability woes).

To conclude. For my money, using a class instead of an ID is preferable and in tandem with some kind of modular CSS system, represents best practice CSS writing. So, be mindful of the techniques and understand why they are useful but don’t fear using an ID either. To illustrate where I might use one; if every single page on your CMS has a wrapper ID (e.g. #wrapper), go ahead and set the margins and paddings etc using that ID as a hook. Trust me, the sky won’t fall down. However, if you can control the markup, opt for a class instead. You’ll get no negative impact but possibly an easier life further down the line.

A note on selector performance – it’s worth knowing and understanding that browsers read right to left when looking at your CSS. So the more specific your final selector (often termed the ‘key’ selector) can be the better. For example, if you had a bunch of links in the footer of a page instead of writing:


footer a {}

If you can add a class such as .footer-link to them, it will get selected and painted by the browser quicker:


footer .footer-link {}

How much quicker I hear you cry? Not enough for even Superman to notice but arguably enough to make you feel all warm inside because you know it’s faster!

More information
OOCSS – Nicole Sullivan’s Object Orientated CSS
SMACSS – Jonathan Snook – Scalable and Modular Architecture for CSS

Verdict: It can seem excessive at first but there are real benefits to be had in writing CSS the OOCSS way, particularly from a maintainability point of view and for others you work with – especially for larger projects. However, if you are a ‘lone gunman/gunwoman’ working on projects, the benefits are less pronounced and your client is unlikely to see any real tangible benefit (in terms of a faster website for example).

If OOCSS is of interest, you might also want to check out Jonathan Snook’s SMACCS project. It’s got more documentation, a book to accompany the project and follows similar principles.

Using over-qualified and overly specific selectors

What are over-qualified and over-specific selectors? The two phrases are often used interchangeably but there is arguably some difference. My take is that an over-qualified selector is one where a selector itself is more ‘qualified’ than it needs to be. For example:


header#banner {}

In that case a header element with an ID of ‘banner’ – when just ‘header’ or ‘#banner’ could have done the same job. However, there may be times when you feel it’s preferable to write a rule that way, perhaps for your own sanity or you want to be clear in your CSS that it’s the ‘aside.sidebar’ you are styling (as an aside, I used both over-qualified and over-specific rules to display CSS in my book) and not just ‘.sidebar’. Doing so won’t effect the way the site displays but over-qualifying selectors makes it more difficult to re-use the contents of rules and adds code where it isn’t needed. Just be aware that where possible for production code, the less specific you can make a selector, means it is generally going to be easier to work with down the line.

Over-specificity on the other hand means using rules that are more specific than they need to be. Here’s an example:


#container .callout-area ul#callout-one li.callout-list a.callout-link {
  color: #bfbfbf;
} 

I know when I started using CSS I often used to end with rules like this! What I should have had in my CSS is actually:


.callout-link {
  color: #bfbfbf;
}

The point is, as soon as you over-qualify one rule that way, it makes it very difficult to override or target other associated elements – as you then need a rule more specific than the last.

This problem is facing a resurgence with pre-processors. Don’t hate the pre-processor, hate the user! Because pre-processors can nest rules, it’s very easy to write rules that are 4, 5, 6 or more levels deep and get yourself in a real tangle. So in short, unless you have to, don’t over-qualify selectors!

Verdict: Try to never have CSS rules more than 3 levels of selector deep and the less the better. The more often you can use a single selector on a rule, the easier you (and others) will find it to troubleshoot styles and fix them. This benefits you more than the user of a website. There are no real tangible benefits of writing the CSS this way – whether you write them with a hundred selectors or one it won’t make much difference to the viewer of the website but it will make your life a lot easier, possibly saving you some hair loss along the way (yes, girls, you too).

HTML

Semantics

Semantics essentially means ‘meaning’ so when people talk about semantics in reference to HTML it typically means using the right element (and class names) in markup. Things have improved a lot with HTML5 and I go into all the HTML5 elements in my book ‘Responsive web design with HTML5 and CSS3’ and WAY BACK in this blog post.
This is a simple thing to understand and get your head around so there is no good reason not to be using (or trying to) the right element in the right place in your markup. Where you use things like H1 tags is also important, not just for Search Engine Optimisation but it also makes your pages/systems make sense elsewhere. For example, the whole point of the HTML5 article tag is so that the contents could be lifted, placed elsewhere and still make sense a self-contained article.

When it comes to classes on elements I’m less anal. For example, to go back to our warning box from earlier. Which of the classes would be right to use in the markup?


content

To be honest – I really don’t think it matters much. Let me qualify that… As long as you (or your team) has some conventions in place (a style guide for example) for understanding what a class is for and does, from a markup and semantic perspective I don’t think it’s a big deal.

From a convenience perspective, I think it makes a lot of sense to have established names or types of names and naming conventions you use and carry from project to project. This is even more important for people who work in teams.

It’s also growing increasingly popular to try and name classes and ID’s with intent. So for example ‘.warning-box’ would be better than ‘.red-box’ because the latter indicates the appearance of the box (red), not the intent of the box (to warn people). However, there are just as many people who would rather see classes that indicate the appearance. In the end, you pays your money, you takes your chances…

Read more
A great post about all of this semantic business is over at Nicolas Gallagher’s website. .
Interesting post about Semantics by Divya Manian (of HTML5 Boilerplate fame) on the Smashing Website.
Jeremy Keith’s response to Divya’s article – again, well worth a read.

Verdict: Understand HTML5 elements and use classes to suit you/your teams needs but don’t stress over it.

JavaScript

Of all the topics I’ve covered here, JavaScript is the area I know least about. Therefore, my thoughts here are more limited…

Concatenation

Concatenation is the practice of combining separate files (usually JavaScript or CSS) into a single file. The point of this is that each separate file in a website requires a HTTP request. Consider this exchange between browser and server:

Browser: Hi!

Server: Hi!

Browser: Can I have the carousel.js file?

Server: Sure, here you go…

Browser: Can I have the jquery.js file?

Server: Sure, here you go…

Browser: Can I have the accordion.js file?

Server: Sure, here you go. Anything else..?

Browser: Can I have the main.css file?

Server: Sure, here you go… That it?

Browser: Can I have the jquery-ui.js file?

Browser: Can I have the easing.js file

Server: Sure, here you go…

Browser: Can I have the desktop.css file

Server (looking bored): Sure, here you go…

And on and on it goes. When you use a CMS (Content Management System), this problem can get ugly fast. Plugins often load their own CSS and JS files and you end up with LOADS of extra files being loaded and this can start to be a problem. However, if you combine all the CSS into one or two files and all the JS into one or two files, things might be more like this:

Browser: Can I have the plugins.js file

Server: Sure, here you go…

Browser: Can I have the script.js file

Server: Sure, here you go…

And that would be all the JavaScript loaded in just a couple of requests. If you use HTML5 Boilerplate or employ a similar technique, you will be used to this practice – add all the plugins into a single file (e.g. plugins.js) and then call them and add your own specifics in a second file (e.g. typically called script.js or main.js).

Tools to help concatenate JavaScript:

CodeKit (OSX)
W3 Total Cache plugin for WordPress (this can do the same thing but on the server, I consider this almost essential for a WordPress website)

Verdict: Where you can, concatenate CSS and JS files into one. At worst, you can do this manually. Just copy and paste all the different plugin files you are using (e.g. Flexslider, FitVids, jScrollpane) into one different file and name it accordingly (e.g. plugins.js). However, a tool like CodeKit can do it for you.

If you run a CMS system, look for tools and plugins that can do it for you on the CMS side of things. This will cover the situations where plugins installed on the server are adding their own styles.

However you concatenate, make sure you fully test all functionality after concatenating your files. Occasionally JS is dependant upon some other piece of JS that needs to be in the correct order.

Compression

Just like CSS compression, it’s important that when you upload JavaScript for production you compress it. Typically, if you are concatenating your JavaScript (which of course you are, right?) for production, the next step is to compress it. There are lots of free tools to do this and many text editors have plugins if they don’t have the functionality includes. Here’s a few to kick off with…

Tools to aid JS compression
JavaScript compressor online (copy and paste your code in)
Excellent PHP and Web toolkit for Coda
YUI Compressor for Sublime Text 2

Verdict: Do it. It’s easy and benefits every user of the site.

Conclusion

It can be a mine field when you are just getting into front end web development to know what techniques and best practices are worth your time. Hopefully, if you are just starting out, some of this information will be useful. However, if you have ended up here and are interested in knowing more, but don’t know who and what you should be listening to, take a look at these other people (all far smarter than me):

Further Reading
CSS: Chris Coyier’s CSS Tricks
All sorts: Nicholas Gallagher
All sorts: Paul Irish, particularly of interest is his front-end feed.
Website Optimisation: Steve Souders

Podcasts:
I like: Shop Talk Show, Non-breaking space, Web Ahead & The Big Web Show.