nooshu - Matt Hobbs' Web Development Blog

Kneeling on the shoulders of giants

Category: Ramblings

A random ramble from the large squidgy organ inside my skull.

Writing efficient CSS selectors

With modern browsers getting quicker with every new version number it’s easy to fall into the trap of writing inefficient code. A page will run super quick on the latest version on Chrome or Firefox, but you also have to consider older browsers and mobile devices. That shiny new web application that uses some super fancy CSS selectors may be unusable on certain devices due to its limited hardware. That’s not to say you shouldn’t be using super fancy selectors; you just have to be careful to consider your target audience, and use them in the most efficient way possible.

The first thing to note about CSS selectors is they don’t work in the way you’d expect. In the west we read a page from left to right. Reading a CSS selector, you’d expect that’s what the browser does as well. Wrong! The browser actually reads a selector from right to left (in Mozilla’s case anyway, and most likely in others too). So take the following CSS as an example:

1
2
3
4
5
body #wrapper .article ul.meta li a {
    font-weight: 700;
    text-decoration: none;
    font-family: Arial;
}

The browser first looks for all the anchor tags (called the “key” as it’s the rightmost selector), then looks at the list items, it evaluates those and throws away the results that don’t match. Next the browser moves onto elements with a class of “meta”, throwing out results that don’t match and so on… you get the idea! There’s so much redundancy in the above selector, it could easily be cut down to:

1
2
3
4
5
.meta a {
    font-weight: 700;
    text-decoration: none;
    font-family: Arial;
}

This example is much more efficient. There are less rules for the browser to evaluate, it’s much easier to read and if you apply minimal selectors across your whole stylesheet you will notice a big difference in file size. The key to writing efficient selectors is to be as specific as possible. Whatever you do don’t write this:

1
2
3
4
body * {
    margin: 0;
    padding: 0;
}

The universal selector(*) is bad (even body isn’t needed)! You are targeting every single element in the DOM and setting it’s padding and margin to zero. For a large page that could easily be thousands of elements!

I actually inspected the stylesheet for this website and went over it with a fine tooth comb. I found many additional selectors that just weren’t needed. The size of my stylesheet went from 18.3kB down to 16.5kB, a saving of 1.8kB. It doesn’t sound a lot in terms of file size, but that’s a whole lot of selectors the browser no longer has to evaluate to render the page.

Luckily there are tools available that can help you make your CSS more efficient, as well as many other areas of your website too. The first tool I’d recommend is called Page Speed, created by Google. The Page Speed extension is available on both Chrome and Firefox. Once installed you have the option to run it on any page; it will give you an overall score for that page and recommendations on how to improve it.

Google Page Speed results for Nooshu.com.

Page Speed results for this site. Note the "Use efficient CSS selectors" drop down.

The second tool I’d recommend is Opera’s Dragonfly. Dragonfly (similar to Firebug, in name at least) is Opera’s developer toolkit, much like Web Inspector for Chrome. An awesome feature that Dragonfly has, that other toolkits don’t is “style recalculation”. Style recalculation gives you a breakdown of all the selectors that were run on the page, how long they took to evaluate and how many elements they hit along the way (hits).

Opera's Dragonfly debugger in action on nooshu.com.

Dragonfly gives you an extremely useful breakdown of what selectors were used and how long they took to evaluate.

If you look closely at the results in the image above, you will see that the selectors with the most number of hits are the ones involving the universal selector(*), as you would expect. You may also notice that most of the timings say 0.0ms which isn’t very helpful. This is due to the fact that the size of the DOM being tested is very small, and timing to 1 decimal place isn’t accurate enough to show the actual time it took to evaluate. If you were to run this test on a huge page, say the HTML5 Specification for example, you would really be able see the difference in CSS selector efficiency.

This feature of Dragonfly is very new and is still in testing. There are a few issues still to be ironed out in future releases but it’s definitely a tool to keep in your bookmarks.

A word of warning when it comes to writing efficient selectors. I found myself trying to make the selectors so efficient it was becoming quite hard to pin-point where exactly on the site they were being used. If you have a very specific area of a site you are trying to target, it is easier to read if you have the selectors starting with an ID reflecting that area. You then know for certain that the changes you make won’t affect other parts of the site. Also remember that removing “unused” selectors will affect the specificity of the rule. You could end up breaking something, as what you thought was an unused selector was actually used in overriding another rule.

Having too many descendent selectors is something that Page Speed frowns upon, but as with all things in life it’s a case of finding that happy medium. In this case it’s between efficient selectors and CSS that is easy to read and maintain (for you and other developers).

Embracing Git for version control

For many years I’ve been using Subversion (SVN) as my version control of choice. It’s been a part of my deployment process, all of my work is in Subversion, even the small demos I’ve created are in a repository. It’s a good feeling to know that if your laptop dies (or is stolen), all your work is backed up on a remote server.

Recently I’ve heard many developers raving about Git, and I’ve looked at libraries and code snippets that are using it, so I thought I’d check it out and see what all the fuss is about. After a couple of hours reading up and watching a few tutorials I’m genuinely excited about using it in future projects. It really is that good! So, what’s so good about it then you may ask? Well here are a few points that stood out for me:

  • Easy to install and start using (Windows has a simple installer)
  • Distributed version control, so no need for a central server
  • Runs on your local machine, no need to connected to the internet to commit(!)
  • Very clean, it only creates one git directory for the whole repository (no hidden .svn’s everywhere)
  • Incredibly easy to branch and merge your code (this is a big plus!)
  • It’s simple to use Git with SVN, no need to abandon your SVN repositories. Git can pull & push directly into an existing SVN repository!

I’d heard developers saying how easy it was to branch and merge your code using Git, I assumed they were exaggerating. But no, it really is simple:

1
2
3
4
5
6
7
8
#create a new branch in my repository
git branch my_new_branch

#move to the new branch for commits etc
git checkout my_new_branch

#finished with the branch, so lets merge it back into master
git merge my_new_branch

One of the most amazing parts of Git that blew me away: when you jump between branches it automatically updates your file structure accordingly! So lets say you have a new set of files in a new branch, and you need to jump back to master (trunk) to make some changes. Simply run ‘git checkout master’, the new branch files will be ‘removed’ and stored away until you are back on the new branch where they were added. Amazing!

The feature that really sold Git to me was the stash command. So many times I’ve been working on a project and got half way through some changes, only to have to fix a bug in the original version. So you copy the modified files somewhere, undo all your changes, fix the bug, copy the files over and start where you left off. Not fun! Git and the stash command come to the rescue:

1
2
3
4
5
6
#store your current changes in a 'clipboard' so they can be seen again later
git stash

#you are now working on the unmodified version of the branch
#after you've fixed the issue, start from where you left off by applying the stash
git stash apply

Another huge advantage Git has is how simple it is to share code between developers. It only takes a couple of commands to clone another repository. Once you have a local copy (clone), you can change whatever you like. Make the project better (or break it horribly, it’s up to you). For an example of how powerful social coding is take a look at Github. The 3D JavaScript library three.js for example has over 4000 people watching and 400+ people have forked (cloned) the repository. If your version adds a cool new feature or fixes a bug, it can easily be merged back into the original project!

If you are interested in learning how to use Git there are some superb resources available. For people who like screencasts I highly recommend watching the one created by Peepcode. It’s only $9 (US), 1 hour-long and will get you up and running with Git in no time at all! Here are some other resources I found useful:

Right, I’m off to start committing to a repository while travelling on a train to work when I don’t have an internet connection (warm fuzzy feeling enabled)!

Back to my desk (down under)

Well that was a quick three months! Travelling around south-east Asia was incredible! So many memories and stories to take away from the experience. Unfortunately all good things have to come to an end, so back to work it is. Actually I’ve been looking forward to getting back to work for a couple of weeks, itching to start using the latest technologies the web has to offer.

A lot can change on the web in three months; so in order to get my head around what’s new, I’ve compiled a list of exciting developments and changes in the Web Developer community (in no particular order).

Browsers

Thankfully the browser war has started again (this time for the better) and it certainly hasn’t slowed down in the last three months!

Some amazing news first; Has Internet Explorers browser market share finally dropped below 50%? Well according to Statcounter it has (oh please let it be true!). As with all statistics you have to be careful how you interpret the data. A more important statistic would be how that 50% is broken down. How many users are still using IE6? If corporations are still sticking with IE6 due to internal tools and upgrade cost, that value won’t be changing any time soon (boo!).

WebGL is the big thing on the web at the moment. Incredible graphics rendered directly in the browser (no Flash required!). Of course Microsoft being Microsoft, they aren’t going to support it. To be fair they do give a good excuse; the specification isn’t 100% set, so they aren’t going to implement it (but when has that ever stopped them before?). Luckily for developers a small team in Russia have decided to add it themselves by creating a plug-in for IE (for non-commercial use) called IEWebGL. It’s not ideal but it’s better than nothing!

There’s been big changes at Firefox over the past three months. The Firefox team have now adopted a six week release schedule just like Chrome. So while I’ve been away we’ve had version 6,7 and 8. There’s even talk of Aurora 10 (a.k.a. Firefox 10) on the horizon. Mozilla also seem to have adopted the ‘channel’ route for deployment, where by you can join the stable, beta or nightly channel depending on how brave you are. You can receive a new version of Firefox every few days (or sometimes a broken version) if you so wish. I’m hoping they also adopt the ‘delta’ update strategy that Chrome uses; no need to download the whole installer every time, only the parts that have changed. On a side note, Firefox now gets 100% on the Acid3 test, so well done to Mozilla for achieving that (if that type of browser comparison floats your boat).

I love this little addition; in the latest nightly versions of Firefox, Mozilla has added support for the draft JoystickAPI. What an incredibly simple idea, it never even occurred to me! The API allows a browser to communicate directly with a joystick / gamepad, meaning you can control that snazzy HTML5 game you’ve written just like you would on a games console. There’s a breakdown of what is supported on the API page including handy code examples. All you need is a joystick that’s supported by your PC or Mac. It looks like a standard Xbox360 controller will work, and they’re fairly cheap to buy. I May just have to add that to my Christmas list this year and give it a whirl!

With the IE browser market share (apparently) going below 50%, it looks like Chrome could be set to take number 2 spot from Firefox very soon. I must admit, I’m not too bothered about who’s in second place; as long as all browser vendors keep improving their products I’m a very happy developer. More competition equals better browsers for all. When one of the ‘good’ browsers gets to number one, then I will celebrate.

At the start of October Google unveiled their new Dart programming language which is supposed to replace JavaScript as the working language on open web platforms. Dart will compile to ECMAScript 3 on the fly for non-Dart compatible browsers. There’s even a simple IDE so you can start playing around with a bit of Dart right now. Will it catch on? Who knows, only time will tell.

Last but not least the browser that everyone forgets about (but it’s actually an excellent browser), Opera. At the start of October they released Opera 12 alpha, which finally supports WebGL! Great news for Opera and WebGL. As it looks like WebGL is here to stay, maybe it’s time the IE team reconsidered its position? Let’s hope they do.

Chrome is about to replace Firefox at the number 2 spot.

Will Chrome overtake Firefox for browser market share in November?

JavaScript

The big event (in Europe at least) that happened while I was away was JSConf.eu, a 2 day conference dedicated to the JavaScript programming language. This year it was held in Berlin, Germany, somewhere I’ve never been (but have heard many great things about). I wish I could have been there, a couple of the talks I’d loved to have seen include “Magic Wand for surface generation – Voxels with JS” and “Connecting the real world to node“. Luckily for those of us who couldn’t be there videos of most of the talks are available online.

Talking of Node, the development team has been bug fixing and adding lots of lovely new features to the code base, and it is now up to version 0.6.0. A point that really caught my attention was the work regarding Windows support. Being a Windows user myself it’s always nice to know the Windows platform is being considered in future development. Looking at the performance statistics in the 0.6.0 blog post, the team have made huge improvements by supporting native APIs (rather than through Cygwin).

Note: As I was writing this blog post Node 0.6.1 was released and it now comes with a Windows installer (MSI).

JSConf.eu took place in Berlin in 2011

Lots of lovely JavaScript geeking out at this years JSConf.eu.

jQuery

For users of jQuery (myself included) it’s been a very busy three months. There have been three new versions released (not including betas and RC’s), 1.6.3, 1.6.4 and 1.7. Here are some of the key features that caught my eye in each version:

  • 1.6.3: requestAnimationFrame API has been removed for animations due to strange goings on when animated tabs are hidden from view. The team plans to re-implement it in a later version.
  • 1.6.4: Minor bug fix release.
  • 1.7: Big changes in the way events are bound (and unbound) to elements. There’s a whole new .on(), .off() event API which aims to unify all the ways of attaching events in jQuery. Also, as mentioned on the jQuery blog they are shorter to type!

For version 1.8 the jQuery team is planning on slimming down the library to reduce it’s overall gzipped file size. They are asking for feedback from the community as to what should be removed and offloaded into a separate plug-in, or maybe even removed all together. There are now so many methods available to a developer, a lot of which are probably never used; I can see why they are looking to slim it down. Maintaining rarely used code is never fun.

I personally would like to see the animations offloaded to a separate plug-in, as for most projects I never use them. I’d happily add the animation plug-in back in if and when needed. Maybe this could be the start of a more modular version of jQuery; by that I mean something along the lines of the MooTools core builder. Creating a custom jQuery build, with only the parts you need really would be a great option. I’m sure lots of other jQuery developers would be against it, but each to their own.

Last in the jQuery news is the announcement that there will be a jQuery conference in Oxford, UK in 2012. It’s the first jQuery conference in the UK, and of course I’m now in Australia. Typical! Oh well, maybe next time.

jQuery confrence in the UK in 2012.

The first jQuery conference in the UK while I'm in Australia. Damn!

Three.js

The three.js community has been busy beavering away with lots of cool new demos. It’s incredible how this superb JavaScript library has taken off since mr.doob unleashed it on the web.

I’ve noticed from the Git repository for three.js that the number of updates has really slowed down. Maybe there are things in the pipe line that have yet to be rolled into the Git repository; or maybe it’s a sign of the three.js API stabilising.

One of the major problems I found while working on a few personal projects was the lack of documentation. It really was a case of diving into the library and examples and having a play (fun, but not ideal). Stability will allow the documentation to catch up with the current release, and in turn allow the wider community to develop lots more interesting 3D demos.

Speaking of interesting demos, here’s one that’s been released by HelloEnjoy called Lights – An interactive music experience. I can’t say I’ve heard of Ellie Goulding (I know, I’m old), but it’s a catchy tune and kudos to her record company for pushing the music video envelope. Is interactivity the future of music videos? I hope so!

Lights by Ellie Goulding, lovely interactive music video

Music video using the power of three.js.

Demos

One thing I really missed while I was away was how all this new technology is being applied on the web. It’s always interesting to see how other developers apply technology to problems they encounter. Creating demos is a fun way to learn something new.

First on the list is a bit of face detection using HTML5 and JavaScript. This technique is used in various webcam applications, where you can add things like glasses and masks to your face in real-time. Hours of fun for kids (and developers too). The demo makes use of the CCV JavaScript Face Detection library and HTML5 canvas element. Awesome stuff by @wesbos, and as a bonus there’s a whole blog post with commented code on how he did it.

What do you get when you combine Google maps and WebGL? That’s right, you get MapsGL! Google has enabled the option to view its maps complete with 3D buildings, in the browser, no plug-ins required! Superb news for WebGL as there is no bigger name you want behind you to push the technology into the mainstream. It’s still a little rough around the edges but it looks very promising! You can enable and view a demo here.

Mozilla developer Michael Bebenita has created and released a JavaScript-based H.264 decoder that will run natively in the browser… wow! Nicknamed Broadway, it is based on the open-source decoder that Google uses in the Android OS. Yet another example of how powerful the JavaScript programming language is. To test it you will need a nightly version of Firefox, or you can always view a video from Brendan Eich’s talk at ACM’s annual OOPSLA conference, where he shows it in action. Amazing!

Do you want to help a computer beat a Grandmaster at chess using JavaScript? Well now you can thanks to the Chess@home project. Developers at Joshfire created a project prototype at this years 48 hour Node Knockout contest. It utilises lots of cutting edge technologies. Starting with the Web Workers API in the browser, to Socket.io for communication and a Node.js – MongoDB combination for storing the results. It works by using the spare CPU cycles of browsing users to calculate the best next move. By adding a small Chess@home widget to your website you can help the project defeat a Grandmaster. By making use of the Web Worker API, visitors to your website won’t even notice the difference (users can disable the widget via a check box if they so wish).

Combining Google Maps and WebGL

Google maps goes 3D with MapsGL - Virtual Westminster Abbey

As you can see the Web Development community has been busy over the past few months! Hopefully I picked out most of the important changes. If you think there’s anything I’ve missed that’s a worthy addition, please leave a comment, I’d love to hear about it.

Hanging up my Web Dev boots (for three months)

As of tomorrow evening I will no longer be a resident of this great land called England as I’m setting off to travel the globe for approximately eighteen months (in total). I’ll be spending three months in south-east Asia; as well as having a grandstand seat at the Singapore Grand Prix (yay!).

I land in Sydney, Australia early November and will be looking for Freelance work (for 12 months) when I land. So if there are and Australian agencies looking for an Interface Developer let me know.

I’ll be travelling with my wonderful girlfriend (who will also be Freelancing in Oz). If you’re interested you can follow our progress on our travel blog. We are also on twitter.

Matt and Claire's travel blog

Our travel blog updated as often as possible.

BBQ on the beach here we come!

WordPress 3.2, auto update fail

Today, while on my lunch hour, I decided to auto update my blog to WordPress 3.2. Usually it goes without a hitch; unfortunately today it didn’t. I’m not quite sure what happened but it failed within a couple of seconds. Damn it! It may be a Dreamhost issue as I’ve seen reports of other users having similar issues, or it could be just bad luck.

If you have a similar issue the first thing you may notice, when trying to get to your site is that maintenance mode is “enabled”. To disable this connect to hosting server via FTP (or SSH) and delete the file ‘.maintenance’. The file may be hidden so you may have to enable viewing hidden files in your FTP client. Once deleted you should once again be able to see your site (fingers crossed!).

The next issue I had was not being able to log into my site admin panel. Navigating to the page gave me a horrible fatal PHP error; a sure sign that something was very broken. Not to worry there’s a (fairly) simple fix.

While logged onto your server via FTP or SSH, delete the ‘wp-admin’ and the ‘wp-includes’ folder. Make sure you don’t delete the ‘wp-content’ folder! Once that’s done download a copy of WordPress 3.2, unzip it and upload the unzipped ‘wp-admin’ and the ‘wp-includes’ folders to your server. Once complete you should be able to see your WordPress login page again! Yay!

You may be asked to update your database, go ahead and click the update button and login. Now take in all the goodness that is version 3.2 of WordPress! The guys have done a superb job with the admin panel, love the new design. Glad to hear they have also dropped IE6 support too. About bloody time!

So a quick summary for the tr;dr’s out there:

  1. Maintenance mode on? Delete ‘.maintenance’.
  2. Delete ‘wp-admin’ and the ‘wp-includes’ folders (Not ‘wp-content’!)
  3. Download a copy of WordPress and unzip it.
  4. Upload the unzipped ‘wp-admin’ and the ‘wp-includes’ folders.
  5. Navigate to the admin page, update database and login

Phew, crisis averted! Now’s a good time to reiterate what is mentioned on the updates page. Always remember to back-up your database and files before you run an update. If something does break with the auto update you can always revert to your backup!

Currently on page 1 of 1012345Last »