Thursday, 27 September 2012

Quick note on RegExp#lastIndex

Just a quick note on RegExp#lastIndex: It's misnamed. It's not the "last" index of anything, it's the index of the next character in the string that will be looked at by the regex instance's exec function (if the regex has the global flag and exec is used on a string that's long enough). It's 0 on freshly-created instances. Just useful to remember, if you ever need to set it explicitly (which you're allowed to do), think in terms of "next" rather than "last".

Of course, you hardly ever need to set it explicitly. The only reason I've ever done so was to work around a bug an issue in some JavaScript engines which are pretty outdated now (such as the one in Firefox 3.6, which virtually no one uses anymore). For anyone who doesn't already know about it, that issue was that some engines reused RegExp instances defined by literals in unexpected ways, which is a problem because RegExp instances have state (the aforementioned lastIndex). On those engines, you get surprising results from code like this:

function test(str, expect) {
    var re = /./g,
        m = re.exec(str);
    
    if (m) {
        console.log("Matched: " + m[0] +
                    ", expected: " + expect);
    }
    else {
        console.log("No match, expected " +
                    (expect === null ? "no match" : expect));
    }
}

test("one", "o");
test("two", "t");

If you run that code on most engines, you get the expected results. But on some engines, instead of matching "t" on the second call to test, the regex matches "w" because the instance defined by the literal gets reused (the same instance is used by both calls to test), and of course after the first call its lastIndex is 1. The workaround was to explicitly set re.lastIndex = 0; before calling exec when you were starting a new set of matches, even if it looked like the instance was fresh.

Apparently there was some ambiguity in the spec (gosh) which makes this an interpretation rather than an outright bug, although I suspect I'm not the only one thinking it's pretty clear that two separate instances should be used. It was cleared up in the ES5 spec and Firefox's engine has been doing this right for a while now (since Firefox 4, I think). I expect any other older engines that had this odd interpretation have probably been fixed as well.

Wednesday, 26 September 2012

Incredible. Extraordinary. Inspiring. Beautiful.

Ten years of Hubble photographs of a tiny portion of the night sky, well away from the glare of the Milky Way, deep into the infrared and then corrected back to visible, the eXtreme Deep Field is nothing less than a breathtaking view deep into the Universe. Just...impossibly incredible.

Saturday, 1 September 2012

S3 Adds CORS Support

Some interesting news today: Amazon's S3 now supports CORS, the Cross-Origin Resource Sharing standard. This means that in addition to storing your images, stylesheets, and JavaScript files in S3 as you might be now, you can now also store any static data or templates you want to retrieve via ajax there, assuming your user is using a browser that supports CORS (all modern ones do, one way or another). This isn't a game-changer, there were ways to do this anyway (basically embedding those resources in JavaScript files a'la JSONP), but it just got a bit easier...

Thursday, 23 August 2012

A reminder how Microsoft used to drive web innovation

As IE6 finally rides into the sunset,* Nicholas C. Zakas offers us a reminder of how, in a series of browser releases culminating in IE6, Microsoft introduced many of the key web innovations we use today such as innerHTML, access to all elements (not just forms and such), Ajax, modern events, and several others. This isn't in any way to discount what Netscape and others have done, but it's worth remembering that the browser everyone loves to hate was easily the best browser available when it came out. (Opera made a run at it soon thereafter, but never quite managed to take the lead, mostly because it didn't support legacy non-standard sites well. And then of course, along came Firefox, and then Chrome.) Good read, thanks Nicholas!

(* Unless — huge caveat — you're creating sites for China [21.3% market share], or arguably for Japan [4.7%] or India [3%].)

Tuesday, 14 August 2012

Measuring Scrollbar Size

Normally we want to avoid doing this sort of thing, but sometimes you just end up having no other option: Recently I couldn't avoid doing some sizing logic in JavaScript rather than CSS and markup, and I had to know the size of the scrollbars on specific elements. I found this post by Alexandre Gomes (which in turn was based on a MooTools forum thread; those forums are gone now), which shows a simple way to do it. I modified the code to measure both vertical and horizontal scrollbars and let you specify the element within which to measure in case the styling of that element affects the result, added some comments, and did some cleanup. Works a treat, I've tested it on a wide variety of browsers young and old with good results. Here's the code:

function measureScrollbars(container) {  
    var child, parent,
        wWithout, wWith,
        hWithout, hWith;
  
    // Create a parent div with a fixed size
    parent = document.createElement('div');  
    parent.style.width = "150px";  
    parent.style.height = "150px";  

    // Create a child div that's 100% of the width (granted
    // that would be the default for a div) and which exceeds
    // the parent's height
    child = document.createElement('div');  
    child.style.width = "100%";  
    child.style.height = "200px";  

    // Put them in the DOM
    parent.appendChild(child);  
    container.appendChild(parent);  

    // Measure the width without a scrollbar, then again with
    parent.style.overflow = "hidden";  
    wWithout = child.offsetWidth;  
    parent.style.overflow = "scroll";  
    wWith = child.offsetWidth;  
    if (wWithout === wWith && "clientWidth" in parent) {
        wWith = parent.clientWidth;  
    }
  
    // Now make the child 100% height, and too wide
    child.style.height = "100%";  
    child.style.width = "200px";  

    // Measure without scrollbar, then again with
    parent.style.overflow = "hidden";  
    hWithout = child.offsetHeight;
    parent.style.overflow = "scroll";  
    hWith = child.offsetHeight;  
    if (hWithout === hWith && "clientHeight" in parent) {
        hWith = parent.clientHeight;  
    }
  
    // Done
    container.removeChild(parent);  
    return {
      width:  wWithout - wWith,
      height: hWithout - hWith
    };
}

Or if you want the jQuery-ified version:

function measureScrollbars(container) {
    var child, parent,
        wWithout, wWith,
        hWithout, hWith;

    // Create a parent div with a fixed size
    parent = $('<div>').css({width: "150px", height: "150px"});

    // Create a child div that's 100% of the width (granted
    // that would be the default for a div) and which exceeds
    // the parent's height
    child = $('<div>').css({width: "100%", height: "200px"});

    // Put them in the DOM
    parent.append(child).appendTo(container);

    // Measure the width without a scrollbar, then again with
    parent.css("overflow", "hidden");
    wWithout = child[0].offsetWidth;
    parent.css("overflow", "scroll");
    wWith = child[0].offsetWidth;
    if (wWithout === wWith && "clientWidth" in parent[0]) {
        wWith = parent[0].clientWidth;
    }

    // Now make the child 100% height, and too wide
    child.css({height: "100%", width: "200px"});

    // Measure without scrollbar, then again with
    parent.css("overflow", "hidden");
    hWithout = child[0].offsetHeight;
    parent.css("overflow", "scroll");
    hWith = child[0].offsetHeight;
    if (hWithout === hWith && "clientHeight" in parent[0]) {
        hWith = parent[0].clientHeight;
    }

    // Done
    parent.remove();
    return {
      width:  wWithout - wWith,
      height: hWithout - hWith
    };
}

Happy coding!

Wednesday, 8 August 2012

jQuery - Element cleanup update

For those who saw my jQuery - Cleaning up when elements go away post yesterday, I've updated it showing how we can do this right now, today, without waiting for the enhancement (or if the enhancement is never accepted). Oh, and the enhancement went from six lines to three. Many thanks to Dave Methvin for showing how (in both cases). Enjoy!

Tuesday, 7 August 2012

jQuery - Cleaning up when elements go away

(Updated 08/08/2012.)

Have you ever wanted to get a notification when an element is removed from the DOM so you could clean up? For instance, maybe you have events hooked on a different object (like resize on window) that you want to unhook when the element goes away.

Recently I wanted to, and since I know that jQuery does cleanup when elements are removed (so it can clear out event handlers and its cache for data), I wondered if it triggers an event for us.

It doesn't, but we can still get what we want quite cleanly. I'll describe what I'm hoping we'll be able to do tomorrow, and what we can do today.

Tomorrow (I hope)

We can enhance jQuery to give us an event on cleanup — with just three lines of code and virtually no overhead. Inside jQuery's internal cleanData function, just after the line that currently reads if ( data && data.events ) {, we add this:

if ( data.events.jqdestroy ) {
  jQuery(elem).triggerHandler("jqdestroy");
}

Boom, that's it. Now if we need notification when an element is going away, we just hook up the event:

$("selector_for_the_element").on("jqdestroy", function() {
  // Do your cleanup
});

We use triggerHandler rather than trigger because we don't want bubbling (there's another way we can avoid bubbling, but it requires a couple more lines of code, and triggerHandler is more efficient anyway — thanks to Dave Methvin for that!).

Here's a copy of jQuery 1.8rc1 with the patch, you can play with it here — that latter link is a test page that generates 10,000 elements, 5,000 of which we hook the click event on (so that they have something in data.events), and two of which we hook the jqdestroy event on. Then we call html on the container element to destroy them all and time how long it takes. You can compare that with this version using an unmodified version of 1.8rc1. For me, the times are much of a muchness (on Firefox 14, both versions average ~142ms when the jqdestroy event isn't hooked, and when it is [on two elements] the version that fires it averages ~163ms).

What I like about this is that if nothing has hooked the event, the overhead is at most one extra property check (the if ( data.events.jqdestroy )) per element destroyed (zero overhead for elements that haven't had any events hooked at all), but it enables a completely familiar and straight-forward way to get notifications.

Well, okay, but is there really a need for it? It would seem so: jQuery UI duck-punches cleanData so they can clean up; TinyMCE goes further, monkey-patching several API calls (empty, replaceWith, and others) so it can clean up an editor attached to an element. And of course, I wanted it for my plug-in that needs to unhook window.resize if there are no more active copies of it.

Now, let me clear about something: To my mind, using this event is a last resort. It's a big hammer, and if you used it on a lot of elements, removing those from the DOM could lag a bit. Consider this example which hooks jqdestroy on 5,000 of the 10,000 elements. For me, the elapsed times go from ~163ms when firing it on just two elements to ~450ms firing on 5,000 (again Firefox 14). Now, 5,000 is a lot of elements to hook this event (or any other) on, and anything can be abused, the point is just...don't abuse it. :-) The best use cases for this will be things like TinyMCE's editors, or grid plug-ins that need to handle resize in code, that sort of thing — where there will be only a few elements with the event hooked.

I've opened an enhancement request on the jQuery Trac database for this, offering to do the patch and send a pull request if the idea has legs. If you think this is a good idea, your support would be welcome! I'm not saying we have to do it the specific way I've outlined in this post, I'm totally open to other ways to get there. Three lines of code, near-zero overhead, and a familiar paradigm seems pretty good to me, though.

Today

But what if that enhancement doesn't get adopted? Or if we need to do this right now, today, with the current version of jQuery? Do we have to hack the jQuery file, or resort to monkey-patching?

Nope. In the linked Trac ticket, Dave Methvin showed how we can do it today, by adding our own "special" event and watching for the teardown on it. This uses the event system, but we'll never actually receive the event in the normal way. Here's how it works:

First, we create a "special" event:

$.event.special.ourowndestroy = {
  teardown: function() {
    // Handle it here, `this` is the element being clean up
    console.log(this.id + " being destroyed");
  }
};

Then we force that to occur by hooking the event on the element, even though our handler will never get called:

$("selector_for_the_element").on("ourowndestroy", function() {
  // This is never called
});

Here it is in action using jQuery 1.7.2.

I've put a function there to make the point that the handler is never called (the action is in the teardown function); in reality I'd probably use $.noop or just false (shorthand for a handler that does return false) instead.

Now, when an element is being cleaned up, our teardown function will get called with this pointing at the element in question. Note that if we didn't hook the event on the element, we wouldn't force the teardown, so even though our handler isn't called, that's required.

Note: You'll also get the teardown call if you remove the event handler from the element (and then not when it's cleaned up, as it's not on there anymore), so if you're using this mechanism, either never remove the handler or handle the fact you get the call if you do.

So that's not an ideal way to do it, and it's not the way this stuff is normally done, but it's a passable workaround in the short term — and much better than monkey-patching jQuery's API on the fly.

Happy coding!