Generate HTML5

September 16th, 2010

Having just finished reading Introducing HTML5 I’m rather excited about all the new HTML5 tags and can’t wait to get using them!

One of the new semantic tags is the <time> tag which is used to mark up dates and times so they are readable to both humans and to machines. It does this by including a datetime attribute which contains the relevent date in a standardised format.

For instance:

<p>
   This post was written on <time datetime="2010-09-16T21:28:29+01:00">Thursday evening</time>
<p>

As you can see, the machine readable format is “YYYY-MM-DD” with a “T” to separate the time in the 24-hour format HH:MM. It ends with your timezone’s offset from UTC/GMT.

UPDATE

Ignore everything that follows! As clever commenters pointed out, there is actually a PHP constant for this format – DATE_W3C. All you need to get the current time is…

<?php echo date(DATE_W3C); ?>

All that follows, from the original post, is left for reference only…

To make this easier to generate when dealing with dates in PHP, I have written a function to do this for me, which is below. Feel free to use it and let me know of any suggestions for improvement.

To use the function, pass in a unix timestamp or leave blank to use the current time.

<?php

/** 
 * formats the date passed into format required by 'datetime' attribute of 

Example: view current time in datetime format.

Buy domain names for just $13/year.

Display HTML OL/UL list as comma-separated sentence with CSS

April 21st, 2010

On a site I’m currently working on, it seemed best to display an OL as a list in sentence form.

For example:

<ul class="commaList">
	<li>one</li>
	<li>two</li>
	<li>three</li>
	<li>four</li>
</ul>

Would display as: One, two, three and four.

In case this CSS is of any use to anyone else, I’ve published it as a snippet below.

Please note this uses pseudo-selectors and so will not work in IE, but will gracefully degrade.

/* display ordered list as comma list */
.commaList li:first-child {
	text-transform: capitalize;
}

.commaList li:after{
	content: ',';
	padding-right: 5px;
}

.commaList li:nth-last-child(2):after {
	content: '';
	padding-right: 5px;
}

.commaList li:last-child:before {
	content: 'and ';
	padding-right: 0;
}

.commaList li:last-child:after {
	content: '.';
	clear: both;
}

/* this prevents single item lists from containing commas and 'ands' */
.commaList li:only-of-type:before, .commaList li:only-of-type:after {
	content: '';
	padding: 0;
}

Amazon Link Localizer Greasemonkey Script

September 28th, 2009

This Greasemonkey script will convert links to international Amazon sites into links to your local Amazon site.
So if I link to a product on Amazon.co.uk, you will get a link to that same product on Amazon.com instead.

Greasemonkey is an add-on for Firefox that allows you to run user-generated scripts on the websites you visit. If you haven’t got it yet, download it now, as you’ll need it to install the below script.

Once you’ve installed Greasemonkey, simply click the below link to install the script.

As you’re visiting from US, you’re probably looking for the Amazon.com Script, right?

Download: Amazon.com Link Localiser (or see all options)

Updates

Follow me on Twitter to be sure you hear about new updates.

Amazon Affiliate Link Localizer WordPress Plugin

September 25th, 2009

Download

Current Version: Amazon Affiliate Link Localizer 1.8.3
Last Updated: 19/03/2013

Description

This plugin not only automatically changes any Amazon link on your site to use your affiliate ID, but it also changes the link to point to the user’s local Amazon store.

So if your visitor is visiting from the UK they’ll get a link to Amazon.co.uk, if they’re visiting from the US they’ll get a link to the same product on Amazon.com. Initially, the script looks for a product with the same product ID as the one in your link, but if it can’t find one on the user’s local store, it will link to a search results page searching for the name of your product. This means that it will still be found even if international versions have different product IDs, and if it’s not stocked at all, your user will be shown similar alternatives.

All you have to do is provide all your affiliate IDs!

Support

If you are having any problems with the script, please read the FAQ which solves most common enquiries.

Non-Wordpress version

If you want to achieve the same result on a non-Wordpress site, you can simply install the pure JavaScript version.

See also: Greasemonkey Script

As an Amazon user, you may also be interested in my Amazon Link Localizer Greasemonkey Script which automatically converts links to international Amazon sites into links to your local Amazon site.

So if I link to a product on Amazon.co.uk, and you are a US visitor, you will get a link to that same product on Amazon.com instead.

Updates

Follow me on Twitter to be sure you hear about new updates.

Donations

If you find this plugin helpful and it’s increasing your sales. please consider donating just $1 or more to say thanks for the many, many hours I’ve spent on it. I’d really appreciate it!

Disclosure

If you do not insert your own affiliate IDs the script will use mine. Hopefully this will help fund my book addiction!

How to Speed Up Your Site and Get a YSlow Grade A

August 12th, 2009

When I first launched my homepage it earned a Grade F in Yahoo’s YSlow. This post explains how I decreased load time and achieved a Grade A.

If you’re not familiar with it, YSlow is a Firefox Add-On that integrates with the indispensible Firebug. It measures page performance and provides suggestions on how to make improvements.

The key to improving the speed of you page is to not only reduce the amount of data that is sent to the client, but also the number of requests made to the server. Each time your browser makes an HTTP request from the server, time is wasted setting up a connection and waiting for a response, introducing further delays.

Originally, my homepage and all its assets – images, JavaScript and CSS files – weighed in at 196kb with a total of 46 HTTP requests. It’s now down to 75kb with 16 requests and loads in half the time.

So here’s how you can improve your YSlow grade…

Compress Images

Saved me 18kb
You probably already know you can reduce image filesizes by choosing the optimal file format and saving at the right quality level. What you might not know is that the resultant images can often been compressed further without any loss of quality.

Smush.it is a lossless compression tool (now built into YSlow itself), which in a single click checks your site for any bloated images, compresses them and then pops them all in a handy zip file for you to download.

You’ll find Smush.it under the Tools menu in YSlow.

Remove 404s

Saved me 4kb and 2 HTTP requests
Check Firebug’s Net tab for any red items, these are files which cannot be found. Here you’re wasting an HTTP request and downloading a 404 page you don’t need. I was surprised to see that I actually had a couple 404s from a Lytebox CSS file.

Remove unused CSS

Saved me 1kb
Firefox add-on Dust-Me Selectors checks your pages for any CSS selectors which are declared in your CSS but not used by your HTML. Providing these aren’t used in any other pages, these can be removed to save bytes.

Combine JavaScript and CSS files

Saved me 4 HTTP requests
If each of your pages use the same few JavaScript files, try combining them into a single file to remove unnecessary HTTP requests. You can do the same with your CSS files.

Minify JavaScript and CSS

Saved me 15kb
Hopefully you write your CSS and JavaScript to be easy to read and maintain, with plenty of comments, verbose variable names and appropriate use of whitespace. However none of this is of any interest to browsers, so these can all be stripped out by a JavaScript minifier, saving crucial bytes.

Use the JavaScript Compressorator to see how much you can save.
There are a few CSS minifiers around, but I’ve found Robson’s CSS Compressor to give the best results.

Be sure to keep the original uncompressed files for any further development. Name the minified file *.min.js or *.min.css and repoint your HTML files.

Gzip Components

Saved me 53kb
Gzipping your text-based assets (HTML, JavaScript and CSS) allows your webserver to transmit compressed versions of your files, often reducing the filesize by around 70%, and allow the users’ browser to seamlessly unzip it and process it as normal. This is probably the quickest and most effective way to improve your site’s performance.

How you turn on gzip compression depends on what webserver you’re running. If it’s Apache 2, as is most common, then the easiest method it to add the following to your .htaccess file:

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xhtml+xml
AddOutputFilterByType DEFLATE application/x-javascript application/javascript text/javascript text/css

If you’ve not got a .htacess file, simply add a text file called ‘.htaccess’ at the root level of your site containing the above text.

To confirm your files are being gzipped, use Firebug to inspect your headers and look for ‘content encoding: gzip‘.

Create CSS Sprites

Saved 14kb and 8 HTTP requests
Images on a website can often be the biggest abuser of HTTP requests. CSS sprites are a technique to reduce the number of requests necessary by combining multiple images into a single image and then using CSS’s background-position to position them.

To the user, everything looks the same, just a little bit faster.

This can also trim down the filesize a fair bit, especially if you combine images of the same format with similar colours. For instance the images accompanying the links in the sidebar to the right are from a 3kb CSS sprite, but individually the images totalled 11kb.

Use multiple Subdomains

The HTTP specification states that a browser can only download a maximum of 2 files from each domain at any one time. If all your files are on a single domain then your users will waste time queuing up downloads.

So once you’ve reduced your HTTP requests, try spreading them around. I’ve moved my JavaScript, CSS and image files onto separate subdomains allowing the user to make the most of their bandwidth.

Add Expires Header

YSlow suggests that you ‘Add Expires headers’, which basically is a note in the header telling the browser to cache the file until a specific date. It won’t then waste time looking to see if the file has changed until that date.

To implement a long expire header, add the following code to your .htaccess file:

<FilesMatch ".(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
        ExpiresActive On
        ExpiresDefault "access plus 1 year"
</FilesMatch>

This does however complicate maintenance. If you make a change to any of the affected files you’ll need to give it a new filename to prevent the cached version being used. I tend to put the last-modified date in the filename to avoid this.

Configure Entity Tags

Entity tags are used to check if the file in your cache is the same as the one on the server. Yahoo’s problem with them is that this doesn’t work if the site is server from a different server – as might happen on a load-balanced site.

So for most of us, this isn’t really a problem that needs solving. If you want to keep YSlow happy though, you just need to add the following to your .htaccess file:

FileETag none

Image Replacement

Saved 17kb and 12 HTTP requests
Due to limited font support across the web, people often use images to display custom fonts. Along with the accessibility issues this presents, this also has the effect of increasing your page’s footprint.

A more accessible and maintainable solution is to use an image replacement technique such as sIFR, FLIR or Cofun to replicate a font.

I prefer Cufon for a variety of reasons, not least because it’s a purely JavaScript technique meaning it can be nicely minified, combined and compressed. The Cufon script and the JavaScript-encoded font used on this site come to around 12k – far less than the images they replaced and didn’t cost any extra HTTP requests.

Prioritised Loading

Once you’ve completed all the above steps, you can still make your website appear to load quicker.

Placing CSS at the top of the page allows pages to be displayed progressively as it loads.
Place JavaScript at the bottom as it blocks the download of any other content.

Backend Optimisation

As well as improving the speed your content is transmitted, you can improve the speed it is generated. On anything but the most basic static HTML site, there will be some server-side programming and database access slowing down the delivery of your content. Be sure you don’t overlook any opportunities for optimisation here.

If you’re not a backend developer there are still opportunities for improvement, for example by installing a caching plug-in on WordPress.

Conclusion

I completed all the above steps mainly as a learning exercise and because I can’t resist the allure of getting a top grade in anything! However, some of the above ‘solutions’ aren’t necessarily appropriate for every site – it’s up to you to assess how great the potential performance gains are and if they worth the overhead in maintenance.

August 5th, 2009

Apple have been getting more and more bad press recently, mostly revolving around the iPhone and it’s app approval/rejection process which has become increasingly unpredictable.

Hopefully, if enough of us let Apple know what we think of them, they might just listen…

Dear Apple,

Like most of the iPhone’s target audience, I’m a bit of a geek. More specifically I’m a software developer – a role which probably represents an usually high proportion of your iPhone customers.

As such, I’m rather surprised that you’ve chosen to piss us all off so magnificently with the recent heavy-handed implementation of your app-approval policy. I say ‘policy’, but as far as anyone can tell, there isn’t one.

The fact that there are websites out there dedicated to working out what the hell your policy is, makes you look a little bit silly don’t you think?

It’s a shame because the iPhone is a truly wonderful piece of kit, but personally I won’t be buying one until you sort this embarrassment out.

Yours begrudgingly

Pete Williams

Amazon Associate Link Localiser

July 14th, 2009

I’ve been a member of Amazon’s Associate program for a number of years and have posted affiliate links to books discussed on this very blog. The program means that by putting my affiliate ID into any links to Amazon products, I receive a small referral fee.

I’ve always linked to Amazon.co.uk as that’s my local Amazon store, but of course that’s not necessarily true for my visitors – or yours…

To solve this problem, I’ve written some JavaScript and a little bit of PHP which will convert any Amazon links on your page into affiliated links to your visitor’s local Amazon store. So US visitors will get a .com link, whilst UK visitors will get a .co.uk link to the same product.

Download

Setup

Edit amazon-localiser.js to insert your regional Associate IDs into the array at the top, for example:

var arrAffiliates = {
	'co.uk' : 'petewill-19',
	'com'	: 'petewill-20',
	'de'	: 'petewill05-21',
	'fr'	: 'petewill-21',
	'ca'	: 'petewill00-20',
	'jp'	: '',
	'it'	: petewill04-21',
	'cn'	: petewill-23',
	'es'	: petewill0d4-21'
};

If you do not have an ID for each country, you can just leave them blank, as above for .jp.

In most cases, you will also need to set the path to amazon-localiser.php, for example:

var strUrlAjax = '/inc/amazon-localiser.php';

Upload and Embed

As well as linking to amazon-localiser.js you need to link to the Google JS API file (5 kb) or the script will not work. Insert the following code just before your </body> tag:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="amazon-localiser.js"></script>

Upload your modified amazon-localiser.js file, and make sure the above link points to the right location.

Usage

That’s it – job done! You can now just link to any product on any Amazon site with a normal, unaffiliated link and your users will get one affiliated for their country. Initially, the script looks for a product with the same product ID as the one in your link, but if it can’t find one on the user’s local store, it will link to a search results page searching for the name of your product. This means that it will still be found even if international versions have different product IDs, and if it’s not stocked at all, your user will be shown similar alternatives.

Example

The script is running on this page, so hopefully this example should be affiliated specially for you!

Updates

Follow me on Twitter to be sure you hear about new updates.

Donations

If you find this plugin helpful and it’s increasing your sales. please consider donating just $1 or more to say thanks for the many, many hours I’ve spent on it. I’d really appreciate it!

Disclosure

If you do not insert your own affiliate IDs the script will use mine. Hopefully this will help fund my book addiction!

Designers – Leave the interface elements alone!

June 24th, 2009

Most desktop applications make heavy use of standardised GUI components such as drop-down menus, tabs, and buttons. Some applications, often web applications, try something different… and fail.

Flash scrollbars are a classic example

Here’s why you should stick to the standards:

  • Familiarity – people are used to, and expect these consistent elements in applications. They already know how they work and will be frustrated if yours don’t work in the same way.
  • Free research! – You’ll probably find that the original elements underwent much experimentation, analysis and research until an optimum was found. This is all yours for free with the standard element!

As such, it’s important not to bastardise these elements without understanding the thought process behind them. Let’s take a look at some examples…

Tabs

Windows Vista's standard tab interface shows correct tab usage.

Vista's standard tab interface shows correct tab usage.

Tabs are a great interface control – they provide a mechanism to make extra information easily available without overloading the user. When used correctly, as per the standard Windows (see right) and Mac controls they also create a great physical metaphor – new users can relate the interface to traditional paper tabs and know what to expect.

What often happens when people mess with tabs, is that they they break that metaphor. For tabs to work, they need to be a different colour when selected, and that colour should be the same as the page displayed below. Just as they would with paper tabs.

A poor web implementation of tabs.

A poor web implementation of tabs.

The image to the right shows an example where the designers have not thought about this metaphor and as a result have produced less usable tabs. They have lost the affordance of tabs – it’s no longer clear what is selected, nor what clicking the tabs will do.

Someone at IBM put a lot of thought into how tabs would work best – let’s not put it to waste by thinking we know better, not until you understand the though process behind the design.

See Steve Krug’s “Don’t Make Me Think” for more detail on the correct design of tab controls.

Scroll Bars

No honestly, that is a scrollbar!

No honestly, that is an actual scrollbar!

Time and time after again we see designers, often of Flash sites, try and reinvent the scroll bar. Not once have I seen anyone offer an improvement over the standard. As well as the risk that users won’t recognise or understand your scroll bar, they ignore what makes the standard element so good:

  • Recognisable scroll buttons with arrows pointing in direction of movement
  • The slider (or ‘thumb’) gets larger when you have less to scroll, providing a larger target when less accuracy is required
  • Clicking in the trough jumps the content up or down
  • Holding down the mouse makes it scroll faster
  • It works horizontally or vertically
  • Only appears when required
  • Works with mouse scroll wheels

I’ve seen all these rules broken simply because the designers wanted something looking different. It gets worse still when they try and make them behave differently, such as those that scroll on hover, instead of on click.

The example to the right, is possibly the worst scrollbar I’ve come across. So much so that you might struggle to spot it. The plus and minus sign along with the bullet points actually form a disjointed scrollbar. If you hover over plus or minus the content moves vertically within it’s box. If you click a bullet it scrolls to specific points. Clicking or hovering anywhere else does nothing. What makes it worse is that this is a small part of the page not a whole screen, so there’s not even the expectation that it might scroll!

Application Close Button

Photoshop CS4's non-standard close/resize buttons

Photoshop CS4's non-standard close/resize buttons

Here’s the problem that prompted me to write this post in the first place – Photoshop CS4′s close button.

You might be thinking there’s not much to go wrong with that little buttons in the top right of your screen, but therein lies the important factor – they need to be at the top right, the very top right!

The top right corner is one of the easiest places on the screen to reach – you can get there in an instant with just a blind fling of your mouse. Move the button just a coupe pixels in from that corner and you lose this – as Abode have done. Worse still, they’ve made the button smaller which makes it harder to use, as Fitts’ Law explains:

The time required to move to a target area is a function of the distance to and the size of the target.

The edges of your screen are effectively of an infinite depth – however far your arm moves the mouse, the cursor stays at the edge. Therefore they represent the biggest click targets and are prime real estate for common functions.

The positioning of the standard close button is no coincidence. As we’ve found, there’s science and research behind all successful interface design, despite the fact that it may not seem immediately obvious. As such, unless you’ve got a genuine reason not to, please leave the interface elements alone!

It’s been a while…

June 11th, 2009

I’ve not posted for a while, as I’ve been busy putting together my new portfolio page and CV and then integrating the design into this here blog.

I’ve now got a backlog of geeky topics to get blogging about, so fear not – normal service will resume shortly!