thingsinjars

  • 4 Aug 2011

    You must be able to read before you get a library card

    I like JavaScript. JS. ECMAScript. Ol' Jay Scrizzle as nobody calls it.

    I also like jQuery. jQ. jQuizzie. jamiroQuery. Whatever.

    Ignoring the stoopid nicknames I just made up, did you notice how I referred to JavaScript and jQuery separately? I didn't say "I like JavaScript, there are some really great lightbox plugins for it" just the same as I didn't say "I wish there was a way to do indexOf in jQuery".

    I'm regularly amazed at how many new (and some not-so-new) web developers either think they know JavaScript because they know jQuery or wish there was a way to do something in jQuery that they read about in an article about JavaScript. jQuery is a library written to make coding in JavaScript easier. It's made in JavaScript so you can say "jQuery is JavaScript" but only in the same way that "Simon is male". To confuse jQuery as all of JavaScript is the same as saying "Simon is all men" (don't worry, there's still only one of me).

    For most web site or web app development, I do recommend using a library. Personally, I've used jQuery and Prototype extensively and decided I prefer jQuery. Libraries are designed to make coding faster and more intuitive and they can be a great productivity aid. You can get a lot more done quicker. There is a downside, however.

    Downside

    If you're doing what the library was intended to help with, great. Slide this panel up, pop open a modal window, scroll to the bottom of the page and highlight that header. Brilliant. The difficulties come when you're either trying to do something the library wasn't intended to do or something nobody's thought of before or you're just plain doing something wrong. If you are fluent in your library of choice but don't know the JavaScript underpinnings, your usual debugging tools can only help you so far. There will come a point where there's an impenetrable black-box where data goes in and something unexpected comes out. Okay, it's probably still data but it's unexpected data.

    Don't let this point in the process be the discouragement. This is where the fun bit is.

    Learning to read

    Library authors are very clever groups of people. Often large groups. Reading through the unminified source of a library can be an awesomely educational experience as it's usually the culmination of many years best practice. If you want a nice introduction to some of the cool things in jQuery, for instance, check out these videos from Paul Irish:

    • http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/
    • http://paulirish.com/2011/11-more-things-i-learned-from-the-jquery-source/

    I've dug around in jQuery many, many times to try and figure out why something does or doesn't do what it should or shouldn't. The most detailed investigation was probably Investigating IE's innerHTML during which nothing was solved but I found out some cool stuff.

    Learning to write

    The best way to get your head around libraries is to write your own. Yes, there are literally millions of them (not literally) out there already but you don't need to aim for world dominance, that's not the point of writing your own. Start simply, map the dollar symbol to document.getElementById. Done. You've written a tiny library.

    function $(id){ 
        return document.getElementById(id);
    }

    Now you can add some more stuff. Maybe you could check to see if the thing passed to the $ is already an element or if it's a string. That way, you could be a bit more carefree about how you pass things around.

    function $(id){ 
      if(id.nodeType) {
        return id;
      } else {
        return document.getElementById(id);
      }
    }

    Add in a couple of AJAX methods, some array manipulation and before you know it, you've got a full-blown web development toolkit.

    If you're wanting a boilerplate to start your library off, I recommend Adam Sontag's Boilerplate Boilerplate.

    Here's your Library Card

    By now, you've rooted around in the jQuery undergrowth, dug through some of Moo's AJAX and pulled apart Prototype's string manipulation. You've written your own mini library, gotten a bit frustrated and wished you had a community of several thousand contributors to make it more robust. Now you're ready to start getting irked every time someone on Forrst asks if there's a jQuery plugin for charAt. Enjoy.

    This article is modified from a chapter in a book Andrew and I were writing a couple of years ago about web development practical advice. Seeing as we both got too busy to finish it, I'm publishing bits here and there. If you'd like to see these in book form, let me know.

    Geek, Opinion, Javascript, Guides

  • 25 Jul 2011

    Psychopathic megalomaniac vs Obsequious sycophant?

    - or -

    Tabs vs Spaces?

    Which are you? Is there any middle ground?

    In any modern, code-friendly text editor, you can set tab size. This means that one tab can appear to be as wide as a single space character or - more commonly - 2 or 4 spaces. It's even possible in some to set any arbitrary size so there's nothing stopping you setting tabs to be 30 spaces and

    format() {
                                  your code() {
                                                                like;
                                  }
                                  this;
    }

    However you do it, the point is that using tabs allows the reader personal preference.

    Indenting your code using spaces, however, is completely different. A space is always a space. There's actually a simple conversion chart:

    • 1 = One
    • 2 = Two
    • 3 = Three
    • and so on.

    The fundamental difference here is that the person reading the code has no choice about how it's laid out. Tabs means you get to read the code how you want to, spaces means you read the code how I want you to. It's a subtle difference but an important one.

    Space indenting is therefore perfectly suited to psychopathic megalomaniacs who insist their way is right while tab indenting is for obsequious sycophants who are putting the needs of others above themselves. Sure, there may be lots of grades in-between but why let moderation get in the way of a barely coherent point?

    Curiously, neither of these extremes feels a great need to comment their code. One sees no need as their code is for themselves and they already understand it, the other assumes that if they can understand it, its purpose is so obvious as to be trivial. Both are wrong here.

    There's unfortunately no real middle ground here. Teams must agree amongst themselves what side of the fence they fall down on. It is entirely possible to set many text editors to automatically convert tabs to spaces or spaces to tabs on file save but if you're doing that, you'd better hope your favourite diff algorithm ignores white space otherwise version control goes out the window.

    This article is modified from a chapter in a book Andrew and I were writing a couple of years ago about web development practical advice. Seeing as we both got too busy to finish it, I'm publishing bits here and there. If you'd like to see these in book form, let me know.

    Opinion, Development, Geek, Guides

  • 31 May 2011

    HTML5 for Large Public Bodies

    Your country needs you...

    ...to stand at the cutting edge of technology.

    Sounds awfully impressive, don't you think?

    There are quite a few regulations to bear in mind and comply with when developing a website for a Government organisation or any large public body. This has lead to a lot of sites being developed in a very defensive manner, ensuring safe compliance at the expense of a great and consistent user experience.

    This video features a presentation about how large publicly-liable institutions should and can embrace the latest in web technologies without sacrificing standards. By embracing them, in fact.

    The content of this was developed while planning and building the National Museums Scotland website which launched last November. The messages presented are applicable to museums, galleries, swimming pools, councils, anywhere, really.

    If you're a techie person in the cultural or government sector, you might find this useful in convincing others to take advantage of the latest cool (and useful) technologies.

    Video

    HTML5 for Large Public Bodies from Simon Madine on Vimeo.

    Links from the presentation

    • PolyFills
    • .NET magazine article
    • (Almost) complete list of polyfills
    • Dive into HTML5
    • HTML5 Boilerplate
    • Smashing Magazine
    • HTML5 Doctor
    • AlphaGov

    Slideshow

    The source for the slides is available online although it's mostly webkit-friendly. I realise the irony of a presentation about cross-platform HTML5 not being a great example itself of that but it does degrade adequately. If I get the time in the future, I'll tidy it up. An actual good (and relevant) example of cross-platform web technologies is the National Museums Scotland website itself which performs fantastically across all manner of platforms.

    Opinion, Development, Geek, Design, Guides

  • 8 Aug 2010

    The quest for Extreme JavaScript Minification

    As described in detail previously, I've recently taken part in the JS1K competition where you have to squeeze something cool and clever into 1024 bytes of JavaScript. The quest to condense has become quite addictive and I found myself obsessing over every byte. This is the kind of stuff that the Closure Compiler does quite well automatically but there are some cases where you just need to get in there and manually tweak.

    Here are some of the tricks I've picked up in my struggle for extreme minification:

    Basic improvements

    Use short variable names.

    This one's fairly obvious. A more useful addition to this is:

    Shorten long variable names.

    If you're going to be accessing an element more than once, especially if it's a built-in element like 'document', you'll save a few bytes every time you reference it if you create a shortened reference to it.

      document.body.style.overflow="hidden"
      document.body.style.background="red"
      (74 characters)
    

    can shorten to

      d=document;b=d.body;s=b.style;
      s.overflow="hidden";
      s.background="red"
      (69 characters)
    

    and any references to s after are going to save 19 characters every time.

    Remove whitespace

    This one's so obvious, I don't need to mention it.

    Set Interval

    The extremely handy setInterval function can take either a function or a string. If you give it an anonymous function declaration:

      setInterval(function(){x++;y--},10);
    

    You will use up more characters than if you give it just the inside of the function as a string:

      setInterval('x++;y--',10);
    

    But the outcome will be the same.

    Little-used aspects

    Not many people use JavScript's scientific notation unless they're doing scientific stuff but it can be a great byte saver. The number 100 is equivalent to 1 * 10^2 which is represented in JavaScript as 1E2. That's not a great saving for 100 but 1000 is 1E3, 10000 is 1E4. Every time you go up a factor of 10, you save 1 byte.

    Fight your good style tendencies

    In the war against space, you have to bite the bullet and accept that you may need to sacrifice some of your hard-earned practices. But only this once. Don't get in to the habit, okay?

    No zeroes

      0.5  = .5
    

    Yeah, it looks ugly but it works and saves a byte.

    Naked clauses

      if {
        :
        :
      } else y
    

    The y looks so naked out there. No braces to keep it warm. But if you only have one statement in your else clause, you don't need them...

    No semi-final. . . final-semi. . . Semi-colon. No final colon.

    You don't need a semi-colon on your last line, even if it does make it look as though you've stunted its growth.

    The final few bytes

    Operator precedence

    You don't need brackets. Brackets are handy for you as the programmer to remember what's going on when and to reduce ambiguity but if you plan correctly, most of the time you won't need brackets to get your arithmetic to work out.

      b.getMilliseconds()/(a*250) 
          is the same as
      b.getMilliseconds()/a/250 
    

    Shorthand notation

      l=l+1;l=l%14;
      l++;l%=14;
      l=++l%14;
    

    The three lines above are equivalent and in order of bytes saved.

    Shorthand CSS

    If you need to set some CSS values in your script, remember to pick the most appropriate short form. Instead of s.background='black', use s.background='#000' but instead of s.background='#F00', use s.background='red'. In the same vein, the statements margin="0px" and margin=0 mean the same but the latter saves bytes.

    Don't be generic

    One final thing to mention is that these little challenges are not the norm. If you find yourself trying to squeeze code down like this you're probably working on a very specific project. Use that to your advantage and see if there are any savings to be made by discarding your usual policies on code reuse. In the JS1K challenge, we're provided with a specific HTML page and an empty script tag. One good saving made here (and mentioned in my previous post) was the way I grabbed the reference to the canvas element. The standard method is to use the id assigned to the canvas.

      d.getElementById('c')
    

    Which is a good generic solution. No matter what else was on the page, no matter what order stuff was in, this would return the canvas. However, we have a very specific case here and the canvas is always going to be in the same place - the first child of the body element. That means we can do this instead:

      b.children[0]
    

    This makes use of the reference we grabbed to the body earlier. If the page were rearranged, this would stop working but as it won't, we've saved 8 bytes.

    In conclusion

    Yes, this is all quite silly but it's also fun and tricky. Attempting these kinds of challenges keep us developers mindful of what it is we actually do and that makes it an extremely productive silly hobby.

    Development, Javascript, Geek, Guides

  • newer posts

Categories

Toys, Guides, Opinion, Geek, Non-geek, Development, Design, CSS, JS, Open-source Ideas, Cartoons, Photos

Shop

Colourful clothes for colourful kids

I'm currently reading

Projects

  • Awsm Street – Kid's clothing
  • Stickture
  • Explanating
  • Open Source Snacks
  • My life in sans-serif
  • My life in monospace
Simon Madine (thingsinjars)

@thingsinjars.com

Hi, I’m Simon Madine and I make music, write books and code.

I’m the Engineering Lead for komment.

© 2025 Simon Madine