Posts tagged "best-practice"

The perils of using JavaScript objects as sets

One question I'm fond of asking in interviews is how to create a set of strings to which values may be added in an efficient manner. Furthermore, membership checks must be reliable and as fast as possible. This post can be considered the model answer. ;)

Higher-level style sheets

Yesterday I used three things for the first time: Sass, Compass, and Ruby. To summarize:

  • I ♥ Sass
  • I ♥ Compass
  • I ♥ Ruby

One's own site is a great place to play with new (or in this case, not so new) web technologies. I decided to get stuck in and manually convert the 1200 line style sheet from CSS to something a bit more awesome. This post documents the most interesting portion of that transformation, which involved this site's archives styles.

Escaping HTML in JavaScript

I recently came across an interesting article at wonko.com on HTML escaping, which provoked me to rewrite Bitbucket's escape function (invoked from within Underscore templates):

function makeSafe(text) {
  return text.replace(/[&<>"'`]/g, function (chr) {
    return '&#' + chr.charCodeAt(0) + ';';
  });
};

This ensures that inserted content cannot escape the confines of a quoted attribute value. Unquoted attributes are more problematic:

Unquoted attribute values are one of the single biggest XSS vectors there is. If you don’t quote your attribute values, you’re essentially leaving the door wide open for naughty people to inject naughty things into your HTML. Very few escaper implementations cover all the edge cases necessary to prevent unquoted attribute values from becoming XSS vectors.

To accommodate unquoted attribute values, the following function could be used instead:

function makeSafe(text) {
  return text.replace(/\W/g, function (chr) {
    return '&#' + chr.charCodeAt(0) + ';';
  });
};

I created a jsPerf test case which confirms that there's a performance hit associated with using this more liberal regular expression. Keep in mind, though, that if “A” takes 1ms to execute and “B” takes ten times as long, “B” still only takes 10ms. Quite often a significant comparative speed difference is insignificant in absolute terms; I'd argue that this is the case here.

Getting truth out of the DOM – Yehuda Katz

Recording of Yehuda Katz's presentation from Bay Area jQuery Conf 2011.

While watching this it finally became clear to me why storing state in the DOM is a terrible idea for complex applications. The approach comes unstuck as soon as one wishes to display an entity more than once in a view (such as in a list–details split view).

Extra comma considered harmful

On , David Chambers wrote:

Hi Douglas,

[…] Moments ago I used JSLint for the first time; I plan to use it frequently from this point forward. I have one question, though, concerning the acceptability of extra commas. Consider the following code snippet:

var ninja = {
    name: 'Hattori Hanzou Masashige',
    shuriken: 5,
    attack: function () {
        if (ninja.shuriken) {
            ninja.shuriken -= 1;
            window.alert('Hai-Ya!');
        }
    },
};

JSLint returns an extra comma error for the unnecessary comma preceding the closing brace. I would argue, though, that this in not an error. As far as I'm aware, this comma will not cause problems.

In fact, quite the opposite is true. If one were to insert an additional property or method after attack one would not need to remember to first add a comma. In Django it's considered best practice to include a comma after every item (including the last) in a one item per line collection for this very reason.

I thought I'd give you my two cents, anyway. :)

Regards,

David Chambers

On , Douglas Crockford wrote:

Your awareness is incorrect. Have you tested on IE6?

CSS image switcher (done the right way)

Chris Coyier has done it again. Compelled me to stay up all night, that is (it's 7am as I type this). In Chris's latest screencast, CSS Image Switcher, he demonstrates how to create an "image switcher" using CSS. The problem, though, is that his process is wrong.

Incorrect process

  1. What effect or experience do I want to create?
  2. How can I achieve this using CSS (and JavaScript if necessary)?
  3. What can my markup do to help me?

Correct process

  1. What effect or experience do I want to create?
  2. What is the most correct and meaningful way to describe the content?
  3. How can I achieve the desired effect or experience (or something close to it) without altering my markup?

Captions over images

This is my response to Chris Coyier's screencast titled jQuery Part 3 – Image Title Plugin which I watched a couple of days ago. Something didn't sit right with me at the time, and I've now worked out what it was: JavaScript is not required!

I'll present a JavaScript-free approach for displaying captions over images that uses truly meaningful markup.

Associative arrays in JavaScript

JavaScript does not have associative arrays. (This will be old news to many.)

Confusion arises from the fact that array syntax in JavaScript is very similar to array syntax in PHP, a language that does have associative arrays. Additionally, any object in JavaScript can be treated as an associative array. This means that if one creates a JavaScript Array object and proceeds to use PHP's associative array syntax in an attempt to add items to it, one will succeed in assigning it attribute–value pairs. The object in question need not be an Array for this to work, though, so for the sake of clarity using a vanilla Object is advisable.

To gain a more detailed understanding of why JavaScript appears to have associative arrays, read JavaScript "Associative Arrays" Considered Harmful.

PHP print_filesize function

Recently I've been on a drive to eliminate dependencies from my code and other areas, such as blog posts. For those who create content for the Web, a reasonably common task is to provide links to files that can be downloaded. It is considered good practice to include an indication of a file's size; for example: favicon.ico (3 KB).

As I was about to hard-code a file's size into a blog post recently, I thought to myself: Will I remember to update this if the file's size changes? More importantly, should I be required to remember such things? The answer, of course, is no. I set about writing a function that would allow the file's size to be displayed dynamically.