HTML5, CSS3, jQuery, JSON, Responsive Design...

Speedier responses for iPhone web apps

Michael Brown   June 2 2012 11:32:37 PM
A little known fact - well, I didn't know it, anyway! - is that the iPhone is actually quite slow at responding to JavaScript click events.  This small Javascript app should demonstrate.  Browse to it on an iPhone and you should see that the Touch button responds noticeably more quickly than does the Click button, and yet the handling code is virtually the same.  The only difference is that they are responding to two different events.  Here's how those events are bound to the two buttons using jQuery:

$("#butClick").bind('click', function() {
alert("Handler for click event.");
$('#butTouch').bind('touchstart', function() {
alert('Handler for touchstart event');

The Touch button is bound to the touchstart event, which is available on touchscreen devices.

In an ideal world, you'd like your web app to be responding to touchstart events on the iPhone and click events on desktops etc, and without having to write tons of if statements in your code.  This turns out to be quite easy.

First, you need to detect whether the touchstart event is available on the current platform, which I've done below by seeing if the document.body.ontouchstart is defined in the current browser.  If so, I change my global variable browserFastestClick to "touchstart" from its default value of "click".  Having set this variable to the correct value, I simply use it on the bind statements where I would previously have hard-coded them to "click" (or "touchstart").

var browserFastestClick = "click";

if (typeof document.body.ontouchstart !== "undefined") {
      browserFastestClick = "touchstart";

$("#butTouchOrClick").bind(browserFastestClick, function() {
alert("Button bound to " + browserFastestClick + " event on this platform.");

The Dynamic button is bound to a touchstart event on a touchscreen device and to a click event on a non-touchscreen device.  This is a very simplistic either/or solution, however.  If you have a touchscreen desktop, then you'd need your app to respond to both touchstart and mouse click events because you could be using either at any time.

Note: I've only tested this on an iPhone.  I've no idea if non-iOS devices such as an Android get a similar speed boost by using touchstart rather than click events.  Android phones should also get a similar speed boost by using touchstart, although I've only tested that on the Android Emulator, using Android 4.0.3.  Please let me know in the comments if you are able to test it with actual Android hardware.

No Comments Found