Skip Navigation

Ramblings from the team at zinc Roe

Metal Fish Eggs

Beautiful Code

Beautiful Code asks well-known (and not so well-known) programmers to discuss the most beautiful piece of code they know.

From the preface:

For some, it lives in the small details of elegantly crafted software. Others find beauty in the big picture — in how a program’s structure allows it to evolve gracefully over time, or in the techniques used to build it.

Reading the first few chapters of the shiny new copy of Beautiful Code in the office has me thinking — what’s the most beautiful piece of code I’ve ever written? I took a little digging, but I think this bit of JavaScript code to preload images would be high on my personal list:

function preload(images) {
    var img = document.createElement('img');
    img.onload = function() {
        this.src = images.shift() || null;
    }
    img.onload();
}

Which would be called like so:

window.onload = function() {
    preload(['1.png', '2.png', '3.png']);
}

I think it’s beautiful because:

  • It’s short. Every byte counts when the client has to download the uncompressed source code.
  • It’s standards-compliant and will work in any browser.
  • It’s efficient. Only one image element is created and closure is used to keep the list of images.
  • It’s clever. It advances to the next image by changing the image’s src property in the onload() event handler. When that image loads, onload() changes src again. Rinse and repeat until there are no more images left and src is set to null, which breaks the loop.
  • When called from within window.onload(), preloading only starts after the rest of the page has finished loading.
  • It’s self-contained and easy to re-use.

So that’s mine… What’s your most beautiful piece of code?

4 comments on Beautiful Code
  1. Jesse Says:

    I’ve chosen a piece of code that’s smaller in size, however not as small as JavaScript image preloading.

    Mine has to do with images also, but deals with PNG images on web sites.

    Internet Explorer (older versions, at least) are not setup inherently to handle alpha transparency in PNG images, but there is scripting to allow it to. In order to have proper placeholders and such I’ve written some PHP code that I’ve used on a few web sites to handle this gracefully.

    The $root variable is set on each page loaded, I always do this to work well with relative links rather than absolute, and can write the same code across files as long as $root is set properly.

    There’s likely more I could add to this function to support additional IMG tag parameters, but this is pretty much all I use most of the time, so I kept it simpler.

    Usage examples:

    <?php echo img_tag('transparent_image.png'); ?>
    <?php echo img_tag('transparent_image.png', 2, 'red', 'This is transparent!', 'right'); ?>
    <?php $png = img_tag('transparent_image.png'); ?>

    And so on…

    Here’s the code:

    <?php
    // $img = image location/name. ie. ../images/title.png
    // $bd = border size
    // $bdc = border colour
    // $alt = alternate text
    // $align = image alignment in reference to text
    function img_tag($img, $bd = 0, $bdc = NULL, $alt = NULL, $align = NULL)
    {
        global $root;
        $ret = null;
        $png = false;
        $ie = false;
     
        // get the image size for width/height parameters
        list($w, $h) = @getimagesize($img);
     
        // find the extension to make sure it's a PNG file being passed
        $ext = explode('.', $img);
        if (strtolower($ext[sizeof($ext) - 1]) == 'png') { $png = true; }
     
        // make sure we only do this for MS IE
        if (stristr($_SERVER['HTTP_USER_AGENT'], 'msie')) { $ie = true; }
     
        // the return variable, start with the image source.
        // - if it's IE and a PNG image, we'll display a 1x1 transparent
        // gif with the correct width/height as a placeholder,
        // otherwise we'll just display the image
        $ret = '<img src="';
        if ($ie && $png) { $ret .= $root . 'images/1x1.gif'; } else { $ret .= $img; }
     
        // add the width/height parameters and start the style tag
        $ret .= '" width="' . $w . '" height="' . $h . '" style="border: ';
     
        // if border size isn't passed, return 0 for no border
        if (!empty($bd)) { $ret .= $bd; } else { $ret .= 0; }
        $ret .= 'px';
     
        // add a solid border with the colour specified
        if (!empty($bdc)) { $ret .= ' solid ' . $bdc; }
        $ret .= ';';
     
        // add the alignment in the style tag too and close style parameter
        if (!empty($align)) { $ret .= ' text-align: ' . $align . ';'; }
        $ret .= '"';
     
        // for good measure, add HTML align parameter too
        if (!empty($align)) { $ret .= ' align="' . $align . '"'; }
     
        // add alt text, if none specified we'll use the image name
        $ret .= ' alt="';
        if (!empty($alt)) { $ret .= $alt; } else { $ret .= $img; }
        $ret .= '"';
     
        // now we verify if it's IE and a PNG we'll add the code to allow IE
        // to handle alpha transparency, as the width/height have to be
        // specified here also. just add another style parameter.
        if ($ie && $png)
        {
            $ret .= ' style="width:' . $w . 'px; height:' . $h . 'px; ' .
            'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' .
            $img . '\', sizingMethod=\'scale\');"';
        }
     
        // close the IMG tag completely
        $ret .= ' />';
     
        // return the variable. this way it can be manipulated or just put into
        // a variable if I don't want it displayed right away. or I can just echo
        // the function name directly to have it print right away.
        return $ret;
    }
    ?>

    Hope this helps someone out there, and hope you can improve on what I’ve done also. One likely improvement I will make is to utilize only one style tag, since IE will have two set in the same image since I’m closing one and opening another. It does however, work for IE prior to version 7 back to 5.5. Version 5.0 and prior are still not going to handle this gracefully, they lack the support for this filter.

    There is likely some caveats to using this also, and I know there’s other ways to use it (an include JS file that is only read by IE browsers (by using an “if lt IE 7.” to load it, and using a script defer tag to render before the page). The above way works for me, and is how I’ll keep it until I’ll need additional features.

  2. keven ages Says:

    We prefer to let javascript handle the image transparency issue. GD can be a pain sometimes for the simple reason that not everyone has it installed and it can use a lot of resources. Great code btw, we just prefer it this way:

    <!-- [if IE 6]> -->
     
    $(document).ready(function() {
        //location of transparent gif
        $.ifixpng('/sites/all/themes/proscenium/images/pixel.gif');
        //fix transparency for div id membership-block
        $('#membership-block').pngfix();
    });

    I was going to post a piece of javascript that I found to be beautiful, however, after reading the example in the post, I think I’ve been trumped.

  3. Luke Says:

    @kevin: don’t be shy, let’s see your beautiful code!

  4. keven ages Says:

    lol fair enough:

    $(document).ready(function(){
        // let's hide all the div's first.  We let jQuery take care of this so that browsers or devices w/o javascript can view the content still
        $(".view-content-health-tips .item-list h3").next().hide();
     
       //add an effect to open the first item in our list to help the user realize how the interface works
        $(".view-content-health-tips .item-list h3:first").next().show("slow");
        $(".my-class-name .item-list h3:first").next().show("slow");
     
        //add a click listener to the headers to toggle the content in the list
        $(".view-content-health-tips .item-list h3").click(function () {
            $(this).next().toggle('normal');
        });
    });

    Essentially this creates a toggle effect for the following xHTML

    block 1
    
    content 1
    content 2.
    content 3
    
    block 2
    
    content 1-1
    content 2-1.
    content 3-1
    

    I love anything that only occupies a few lines of code but is both highly extensive as well as practical.

Your Comment…

You can use these tags: <a> <blockquote> <strong> <em> <strike> <code> <pre> Use <pre lang="LANGUAGE"> for syntax highlighted code blocks.