Category Archives: Javascript

I’m currently working on a front-end build for a site whilst a second (external) team simultaneously develop the back-end. Those guys will later integrate the templates once everything is ready. It’s a fairly common scenario.

We’re in a good position with this project specifically, because although the server-side is a work in progress the developers have provided a full API specification that details all the data that the application will provide, in its entirety. Our work isn’t held up by any architectural decisions yet to be made – the spec is finalised, only the platform to serve data and render our views doesn’t exist yet.

Working from spec, we’re able to create accurate (dummy) data objects and render pages with a templating system to build a limited, realistic, navigable version of the site.

With our data objects in line with their schemas, plus agreeing on a templating system similar to their implementation, should minimise the integration period.

For templating we’re using Mustache, which has a number of server-side and client-side implementation options.

The project is also built with Bootstrap, which makes use of LESS CSS.

Working with LESS, Bootstrap or otherwise, I use the command-line compiler with a custom script to monitors file changes and automatically output the master CSS file as I go. This runs using Jake, a Javascript build tool for Node.js, which I also use to compile and minify Javascript files, plus a few other tasks.

We decided to build on the Node stack with a Javascript implementation of Mustache and a light web framework, Express, to serve our pages and provide URL routing.

Using Express

With Node installed, get Express with npm:

mkdir myapp
cd myapp
npm install express

Create a basic Hello World app in a text file, myapp.js:

var express = require('express'),
app = express();

app.get('/', function(req, res) {
res.send('Hello World');
});

app.listen(3000);
console.log('Listening on port 3000');

Run with the following and visit localhost:3000 in your browser:

node myapp.js

To serve a template with data you’ll need to install a templating engine, create the view and update the app response. The default is Jade:

npm install jade

Create the view file in the default views directory, called simple.jade – print the data:

=message

Update and restart the app file:

app.get('/', function(req, res) {
res.render('simple.jade', {'message': 'Hello World'});
});

Node Toolbox

Restarting the app gets old fast, install nodemon globally to monitor the script for changes and the reload will be automatic:

npm install nodemon -g
nodemon myapp.js

Express will look at the view name extension to load the templating engine. To switch to another, e.g. Mustache, install and configure the app to use a different module. Not all engines provide the same method for Express to render templates, so Consolidate.js maps a bunch of popular options automatically.

npm install consolidate mustache

var engines = require('consolidate');
app.engine('mustache', engines.mustache);

app.get('/', function(req, res) {
res.render('simple.mustache', {'message': 'Hello World'});
});

Update the view with Mustache syntax:

{{ message }}

Also use the engine method to map the .html extension so you don’t have to use .mustache files if you like. The view engine setting saves you from writing the extension in the render method too:

app.engine('html', engines.mustache);
app.set('view engine', 'html');

app.get('/', function(req, res) {
res.render('simple', {'message': 'Hello World'});
});

It’s not great having to write JSON data inline, so use fs to read your JSON from separate files with something like the following:

var fs = require(‘fs’);

var getJSON = function(path) {
var fileContents = fs.readFileSync(path, 'utf8');
return JSON.parse(fileContents);
}

app.get('/', function(req, res) {
var data = getJSON('views/simple.json');
res.render('simple', data);
}

We also wanted support for partials, so we moved to Hogan.js,  a Mustache compiler from Twitter.

Since our environment runs entirely on Node, we’re also able to make use of some freebie cloud hosting, the likes of Heroku and Nodejitsu, for staging at least.

Dependencies for Node projects can be described in a package manifest, specifying modules and version requirements. Our package.json file, in the directory root, looks like this:

{
"name": "simple-express",
"description": "Simple Express template server",
"version": "0.0.1",
"dependencies": {
"express": "3.x",
"nodemon": "0.6.19",
"consolidate": "0.4.0",
"mustache": "0.5.2"
}
}

With a manifest you can run a single command to grab everything you need:

npm install

Nodejitsu use package files to deploy applications, they’ve got a handy interactive cheat sheet exploring the various properties.

Source files: simple-express on Github.

Last week I attended a YDN Tuesday, a developer talk hosted by the Yahoo! Developer Network led by Dirk Ginader, discussing Web Accessibility.

It looks as if these presentations have been running for a while now and they’ve got a good schedule lined up for the coming months. They discuss a decent section of Web development beyond the pure skills – JS, DOM, PHP, OAuth, Web services, Yahoo! technologies and by the looks of things have AJAX, Flex and Ruby on Rails in the pipeline.

They’re also free, which is great when you’re sitting down to hear Yahoo! experts talk about what they do best!

Dirk Ginader is part of the Accessibility Task Force at Yahoo! and tackled developing fully accessible Web applications at every level – covering basic markup, best practices with CSS and accessible Javascript, finishing with a discussion on WAI-ARIA, offering some of his insight gained from working with the standard.

Most people are familiar with the common three-layer development of Web sites, building a core HTML structure, styling with CSS and enhancing functionality with Javascript. In his talk though, Dirk introduced a five-layer development method and spoke about this throughout the sessions.

Dirk Ginader's 5-layer Web development

Building on top of the common three-layer method, Dirk spoke of adding levels of ‘CSS for Javascript’, i.e. adding extra CSS if Javascript is available and enhancing the interface to promote this – and a final layer of WAI-ARIA, the W3C standard for accessible rich Internet applications.

The core layers – HTML, CSS, JS

First though Dirk went into the basics, giving a good exploration of the first shared three layers – reiterating the importance of good, clean HTML, appropriate and logical tab ordering, form building and that it should, obviously, be usable without CSS and Javascript.

Again he reiterated the importance of dividing CSS and Javascript, simply, as it always should be, that CSS is for styling and Javascript is for interaction. CSS can be used achieve a lot of interactivity functionality that would otherwise be controlled by Javascript, but these are akin to hacks, says Dirk.

Another accessibility oversight is the assumption that all users have a mouse or pointing device – and as such, all design is appropriated for mouse control. If your mark-up is good and each ‘level’ of your development has been tested and is robust, your site should be completely navigable with just the Tab and Enter keys. Also, any CSS that uses the mouse-only :hover effects, should also use :focus, which includes active tabbing.

I always feel that approaching Web development in view to adhere to strict standards and to maintain accessibility always helps produce cleaner code and generally minimise errors and cross-browser inconsistencies in the long run anyway.

Dirk spoke about the usefulness of the focus() Javascript function, in bringing users’ attention to alerts, changes, altered screen states and such – especially handy for users with screen readers or screen magnifiers.

On the subject of screen readers, Dirk spoke about how they really work, how they see a Web page and handle the content – talking about loading systems and various reading modes. This was great becausue although I’ve designed for screen readers before, I’ve never seen one being used or had a go myself – and I’m sure I’m not the only one.

CSS for Javascript

The first extra level of Dirk’s five-layer development is in adding CSS when Javascript is available. This means your interface can be altered knowing that Javascript can be used.

You can use Javascript to append an additional class to page elements so that you can use CSS to target and style them. For example, the following line of code adds a class named ‘js’:

document.documentElement.className += ” js”;

You would then style with the follow CSS, where the first declaration is global and the second applied only if Javascript has been found and appended said ‘js’ class to an element:

.module {
/* Both layouts */
}
.js .module {
/* Javascript layout */
}

Enhancing a page in this way isn’t anything new, but it is very cool.

If you’ve heard of the term Progressive Enhancement, then you’ll know why. If you’ve not, you may have heard of Graceful Degradation. Both are methods for handling differences in browser rendering and capability, they’re similar but subtly different.

Graceful degradation, or ‘fault tolerance’, is the controlled handling of single or multiple errors – that when components are at fault, content is not compromised. In developing for the Web, it means focusing on building for the most advanced and capable browsers and dealing with the older, second.

Progressive enhancement turns this idea on it’s head, focusing on building a functioning core and enhancing the design, where possible, when capable.

There are a good few articles on A List Apart about that I strongly recommend bookmarking:

 

The last article, Scott Jehl discusses enhancement with both CSS and Javascript and has a similar trick of appending class names to page objects once Javascript has been detected. He talks about how to test those capabilities and offers a testing script, testUserDevice.js, which runs a number of tests and returns a ‘score’ for your interpretation. As well as offering an amount of detail on top of the alone recognition of Javascript, it even stores the results in a Javascript cookie so the tests don’t have to be run on every page load.

WAI-ARIA

The final layer of hotness is WAI-ARIA, the W3C standard, the recommendation for making today’s RIA and heavily client-scripted Web sites accessible.

WAI-ARIA adds semantic metadata to HTML tags, allowing the developer to add descriptions to page elements to define their roles. For example, declaring that an element is a ‘button’ or a ‘menuitem’. In Dirk’s words, it maps existing and well known OS concepts to custom elements in the browser.

As well as page elements, page sections or ‘landmarks’ can be described too – declaring, for example, a page’s ‘navigation’, ‘banner’ or ‘search’ box – these look very similar to HTML 5.

There’s a great introduction on the Opera Developers site.

WAI-ARIA is not something I’ve used before, but looking at the specification there seems to be a lot of definitions you can add into you code – it looks very extensive.

Although it is ready to use, it will apparently invalidate your code unless you specify a specific DTD. Dirk didn’t actually point to where you can find these, though I’ve seen that you can make them yourself, however I don’t know if this is what he was suggesting.

Dirk has also uploaded his slides onto Slideshare, including the code I’ve used above, you can see them here:

In the lonely cool before dawn, you hear their engines roaring on.