navigator.onLine alternative: serverReachable()

Remy Sharp blogged recently about the issues of the navigator.onLine property and online/offline events. Let see how they can be worked around.

Getting the browser to handle it is hard

As it turns out, this property and those events can currently only be relied on to tell whether and when the user decides to turn on/off the “Work offline” feature of the browser. Indeed, some platforms have specific behaviors that make it hard for the browser to be constantly aware of the computer connectivity: Windows sometime incorrectly report its connectivity after waking up from hibernation, NetworkManager on Linux can’t be trusted because some users bypass it, etc.
This is why, as of Firefox4 and until we can find a reliable alternative, only the user can switch to offline mode.

What onLine doesn’t tell

If you are building a website with offline features, using this property to switch between online and offline mode might not be the best option. Not only can it incorrectly report the connectivity of the computer, but it also doesn’t tell anything about the actual reachability of the server: you might be connected to a network blacklisting the service; you might have no connection but be developing a website locally; or the server could be down…

In any case, it is probably more reliable to simply send a request to the server and fallback to local storage/resources/database when the request fails.

serverReachable()

Following is an example of code you can use to verify that the server is reachable

Improving the AppCache

Last week, Mark Christian & Dustin Diaz published AppCache Facts, a concise and pragmatic documentation about how to write a cache manifest to take your Web applications offline.

AppCache has the potential to benefit many websites, not only in offline scenarios but also on the performance ground. And yet, developers have struggled to use it in their projects because of the initial implementation quirks, the lack of documentation and tooling.

Now that the implementation and documentation parts are good enough, it’s time to get rid of the next papercuts. I gathered an initial list of those little things that could be fixed or improved to make the AppCache useful and convenient:

  • it should be possible to exclude the html file associated with the manifest from the cache,
  • it should be possible to cache resources from other origins on https too,
  • Firefox should stop asking for user permission and let developers see what’s in the AppCache.

What would you add to this list?
Leave a comment, and I’ll make sure the feedback is heard by Mozilla and Google engineers.

Ups and downs

I’m stuck in my home-town because of an annoying backache, I’ll take this opportunity to write a small post.

Down

So I went to Boston and things did not go as planned.

First there was the rain: I ended up walking a quarter of an hour under a heavy rain and arrived at the venue just as if I crossed the Charles by swimming. I was so grateful for the dry jQuery T-shirt they gave us! My laptop was OK but I was still freezing. Was I going to give my first talk in wet pants? Not such an enjoyable perspective…

I was after all dry for the talk, but that did not help much. I was afraid the biggest problem would be my nervousness and my accent, but it turned out that the demo I prepared was too abstract, distracting and did not match the expectations of the audience , probably composed of intermediate/advanced jQuery developers. In the thirty minutes or so that followed the conference I realized all the mistakes I did, and yet it was too late.

I therefore asked Karl Swedberg to write a follow-up post on learningjquery.com with the content that I felt, retrospectively, appropriate for the conf.

Up

You can now read my first post, More Event Delegation with jQuery, on this official jQuery blog. I actually decided to split the original content. There will be a part 4 explaining the way non-bubbling events are made compatible with .live() in jQuery 1.4 (the sections about focus/blur and mouseenter/mouseleave are already written, but the implementation of submit/change/select is not ready yet). The fifth part is going to be shorter, discussing the performance in event delegation with jQuery.

The conference was also a good opportunity to get to meet members of the jQuery community. The few people I had a chance to chat with (mostly foreigners, what a coincidence!) were really nice people. I was thrilled with the announcement of an up-coming jQuery conf in London, I hope I’ll be able to join once again.

What’s next?

First things first, I hope I will heal quickly, staying in bed all day long really doesn’t suit me. I shouldn’t be using a computer right now… I cannot help it.

I’ll be in Praha from the second to the fifth of October for the EU MozCamp. It looks like I’ll see many of the people I met in Madrid, those two days can only be fantastic! And I’ll take two extra days to visit this wonderful city with a friend from uni.

Then it will be time to look for a job… Independence, at last!

EventSound, round 4: now with sounds!

I’ve finally found some samples and I didn’t had to search really far: I took sounds from World of Goo.

So go test the latest version of SoundEvents. You need a browser compatible with HTML5′s audio tag, preferably Firefox. Chrome introduces a delay before playing the sound even though it is cached when you open the page. And I haven’t tested Safari.

The only problem is that I cannot redistribute those sounds since they are not liberally licensed. I tried to use the sounds of Wormux as an alternative but for some reason the sound is not playing in my application even though they do play when I drag & drop them in the browser. It’s too late now, I’ll search for alternatives tomorrow.

Do you know any Open game with interesting samples?

EventSound, round 3

And here we are, the penultimate version of EventSound has been uploaded. And the only feature that is missing for 1.0 is… the sound. It looks like I’ll have to find samples on the Internet now.

I’m rather happy with the development pace of this application. It all started last Saturday and in four days we have something up and running, nice looking and maybe even useful! Altogether the application consists of one static HTML page and two scripts for a total of approx. 350 nice lines of JavaScript/jQuery.

I learned a lot writing this experiment, event delegation with jQuery is not only easy and powerful, but it feels natural. At some point you’ve got the impression to write XBL with this feature. For example there is one event listener for each kind of snippet (one by tab basically). But all of those are listening to the “update” event that can be triggered in three ways:

  • when the content of an input is modified (either by clicking on the scene or typing text)
  • when commented code is clicked
  • when removing the snippet

And then we just do event delegation:

  • once to detect the modification of an input value and triggers the update event for the parent snippet,
  • once to detect the click on commented code and trigger the update event on the parent snippet and modify the color of the code,
  • once to detect the click on the “-” to trigger the update event on the parent snippet and remove it,
  • once to detect the click on the “+” to duplicate the snippet.

And that’s basically it. Create a new tab, add a div with a class “.snippet” in it, then insert an input, a div with a class “.comment”, a link with a class “.remove”, a link with a class “.add” and all those features will work right away. The only thing left to implement is what happens when the snippet is updated. It’s like having behaviours attached to some kind of elements and you compose another element with those building blocks, you give it a specific behaviour and you can in turn duplicate this bigger building block.

Event delegation could be seen as a great advantage for the Open Web as a development platform. Which other technology offers this mechanism out of the box? Although it can be achieved with ActionScript or other technologies, it implies to rethink and reimplement strategies to broadcast events to higher levels… you end up reinventing the DOM!

Just as for the first round of EventSound, I let you find what the last two tabs are for. It should be fairly easy to figure it out.

EventSound, round2

The second iteration of EventSound has been uploaded. It doesn’t make any sound yet (I’m waiting for samples from my brother and my friend Lorenzo) but there are new nice improvements since last time.

EventSound is an application aimed at explaining how events work in the DOM and how to write code relying on events with jQuery. Not only is the interface built with jQuery and jQuery-ui, but the interface itself consists of snippets of JavaScript/jQuery code that can be used to play sounds when events occur on the scene (the left panel). You need to be familiar with the basics of the jQuery syntax to understand those snippets. Fortunately I wrote a quick introduction to jQuery for my final report (see “Dealing with the DOM”).

Illustration of event propagation

You will immediately notice that the bubbling of the events is decomposed on the scene. If you click on an element, you will see the click event being triggered on the element and then all of its ancestors.

Simple listeners

The first thing you can do with the application is to bind event listeners to scene’s elements using the snippets in the bind tab. The only thing you have to do is to fill the space reserved for the CSS selector in a snippet. To do so, there are two possibilities:

  • You look at the source of the scene to search for the classes and ids of its elements. There is no need to use ctrl+U or Firebug for that since I’ve implemented a neo mode: as long as you hold down the control key, you can see the Matrix! Be careful, you cannot dodge bullets.
  • You click in the space reserved for the selector and then click on any element on the scene. Simple, isn’t it?

The neo mode has been implemented just for fun. I read an interesting article by Atul Varma recently about Kids and the Open Web, and I tried to imagine a cool way to introduce non-programmers to the source of a Web page. I came up with this Matrix analogy: the ability to see (and later modify) what makes the Web we live in. Unfortunately it won’t take long before we see a generation of kids who don’t know about the World imagined by the brothers Wachowski.

From here, when you click on an element of the scene, as the bubbling event reaches an element that has a listener attached, the opacity of the listener changes. This is where the “Sound” of “EventSound” should make sense, because you will hear something, in the future, once the samples are ready (guys, if you’re reading me…).

Using those snippets it is also possible to cancel the bubbling of the events in the jQuery way: by returning false. Simply click on the last commented line of code… and pray for this feature to work ; )

Cloning elements and listeners

The second thing you can do in the application is to clone elements of the scene. You need to uncomment the single line of code in the snippet of the “instructions” tab. The next time you will click on an element it will be cloned and inserted gently, as the code suggest: the position and the color of the element is modified and appropriate id and class are set. Don’t take my word on that, enter the Matrix!

There are two comments in a single line of code (resulting in a CSS nightmare), the second one is a true parameter for the clone method which also clones the event listeners. When uncommented, if an event listeners is bound to an element and you clone this element, when a bubbling event reaches the clone, the event will also fire (unless there is a bug in the application, hehe).

Live events

.live() is a function introduced in jQuery 1.3 which brings event delegation to the masses: using this function, instead of binding events to individual elements (and having to clone the listeners when you add an element later), you bind a listener on a higher level and use the bubbling property of events to listen to the events occurring on a lower level.

This time you need to select both the elements on which you want to detect the event, and the higher element that you will use to bind the listener. For that I’m using a special syntax of jQuery where I do not pass only a CSS selector to jQuery, but also a context. Be careful, this syntax only works for event delegation with the upcoming jQuery 1.3.3.

[code lang="js"]
$("<selector>", $("<context>")[0])...
[/code]

Currently, to be successfully set, the context needs to be a DOM element, not a CSS selector, not a jQuery object, simply a DOM element, hence the [0] at the end of my jQuery object. I proposed a patch to be able to get rid of this [0] and thus reduce the number of function calls but it hasn’t been accepted yet.

You can now clone and add elements inside your context without worrying of attaching new listeners, great! And soon or later I hope that my bigger patch will eventually be accepted in jQuery so that you don’t have to worry about performances of event delegation.

And now…

I need your comments as I’m going to reuse this Blog post for my presentation on Saturday. What could be clarified? What could be improved? What did I do wrong? What is good, if any?

In the meantime I’ll work on the last two tabs and start to create my slides.

EventSound, round 1

I’m so happy to be done with my report that I don’t even want to bother about explaining anything about my new projects ; )

This is the best I came up with:
There is now a quite usable version of EventSound online. It is not finished but it shouldn’t be too buggy, it doesn’t make any sound but it does look nice, and I won’t even tell what it actually does. One beer to the one who finds what it is for.

I hope to have the sound and the last three tabs working by Tuesday.

Busy September

My report was just handed-in, I was starting to feel relieved of all the pressure and the work… when I learned that I was going to give a talk at the jQuery conf in Boston and the MozCamp in Praha (in October actually, but in less than one month from now). I’ll be sponsored by Teesside University for Boston, and for Praha I don’t know but I’ve got good friends living over there, I’m not too worried.

No matter how great those news are, it means that I’ll have to prepare my talks and will thus have less time to work on ToDoSo. It doesn’t even mean that the project is on pause, since I will have to use a presentation software for at least one of these talks, and I’d like to use mine!

In September I’ll also have to move from Middlesbrough to Lyon and start to search for a real job!

You can expect to see new projects for the Open Web on this Blog, I’ll soon introduce the first version of “EventSound: audible jQuery events”.