Skip to content

    Frontend System Design

    Mobile Web Performance, Touch and Gestures

    Design for fingers and small screens: tap latency, touch-action, passive listeners, pointer events and cancellation, viewport units, target size and long tasks.

    By Published 13 min read

    • frontend-system-design
    • mobile-web
    • touch
    • gestures
    • pointer-events
    Share

    Standard lessonintermediateFrontend System Design

    Before this: Loading Performance and Core Web Vitals

    What you'll learn: By the end of this lesson you will be able to explain who decides what a touch means (your page or the browser), use touch-action, passive listeners and pointer events so gestures neither lag nor get cancelled, size viewport and touch targets for phones, offer an alternative to every drag, keep the main thread free enough for a tap to respond, and read mobile field data without guessing at numbers.

    Think of a revolving door with a guard. If the guard waits to be sure what someone wants, everyone queues; if the guard guesses early and is wrong, people get hit. A mobile browser is that guard. A finger lands and the browser must decide quickly whether it is a tap, a scroll, a pinch or a drag your page wants. Your job is to tell it enough that it decides early and correctly, and to keep the room behind the door from being blocked.

    This lesson assumes the metrics from loading performance and Core Web Vitals and the main-thread model from the event loop and the main thread; INP and responsiveness covers the metric in depth, and mobile and cross-platform front ends places mobile web among the other approaches. The running example is the product page of the ShopStream grocery marketplace on a phone: a photo carousel, a quantity stepper and an add-to-cart button. The later lesson on responsive, adaptive, PWA and native choices is named in plain text only.

    Verified on 2026-12-02 against MDN, web.dev, Chrome developer documentation and the W3C WCAG 2.2 Understanding pages. No phone or emulator was available. The three Node scripts on this page were run; every claim about how a real touch browser behaves comes from the cited documentation, not from a device test.

    The core idea

    1. The browser owns scrolling and zooming by default. Declaring what your page handles with touch-action lets the browser decide at once instead of waiting for your code.
    2. A gesture can be taken away from you. If the browser decides a touch is a pan or zoom, your page gets pointercancel, and any drag state must be reset.
    3. Latency is a budget spent in three places: waiting to start (input delay), running your handler (processing), and painting the result (presentation). Phones have less to spend, and a long task anywhere spends it.
    4. Touch is imprecise. Targets need size and spacing, and every drag needs a way to do the same thing without dragging.

    From intuition to internals

    The tap and the old 300 ms wait

    For years mobile browsers delayed the click after a tap. Chrome's developer blog says they "applied a 300-350ms delay between touchend and click", because a second tap soon after might be a double-tap to zoom. It says Chrome 32 (2014) removed the delay for mobile-optimized sites while keeping pinch-zoom, and that a viewport meta tag with width=device-width is what tells the browser the page is mobile-ready. MDN documents the CSS route: touch-action: manipulation enables panning and pinch zoom but disables non-standard gestures such as double-tap to zoom, which "removes the need for browsers to delay the generation of click events".

    MDN's recommended viewport setting is width=device-width, and it warns that user-scalable=no "prevents people experiencing low vision conditions from being able to read and understand page content", adding that WCAG requires a minimum of 2x scaling. Never turn off zoom to remove a delay; the two settings above remove it without taking zoom away. MDN gives the same caution for touch-action: none, so use it on a gesture surface and not on whole pages.

    Scrolling and passive listeners

    A scroll starts as a touch. If your touchstart or touchmove listener might call preventDefault(), the browser cannot start scrolling until your listener finishes. MDN states this plainly: the browser "is in general unable to start the default action until the event listener has finished", and a slow listener causes jank. Setting passive: true promises you will not cancel, so scrolling can start at once; if a passive listener calls preventDefault() nothing happens. MDN also says passive defaults to true for wheel, mousewheel, touchstart and touchmove on Window, Document and body, and to false elsewhere, so a listener on an inner element that you do not mean to cancel should say passive: true explicitly.

    overscroll-behavior is the next knob. MDN says mobile browsers "tend to provide a 'bounce' effect or even a page refresh" at a scroll boundary, and that the property can remove unwanted scroll chaining and pull-to-refresh behaviour. contain stops the scroll continuing outside a container (bounce may remain); none also stops the bounce. MDN lists the property as limited availability, so treat it as an enhancement.

    Pointer events and cancellation

    Pointer events give one model for mouse, pen and touch: MDN says they are "designed to create a single DOM event model" for these devices, with pointerType available when you must tell them apart. The event that matters most on a phone is pointercancel. MDN says the browser fires it when "the browser decided to interpret the interaction as a pan/zoom instead". Treat it as the end of the interaction, like pointerup: reset drag state, release capture, never leave a half-dragged element.

    You can prevent the takeover for a gesture surface with touch-action: none on the element (MDN's recommended pattern for a draggable element), or allow only the axis you do not handle: pan-y on a horizontal carousel lets the browser keep vertical page scrolling while your code receives the horizontal movement. setPointerCapture() retargets a pointer's events to one element until release, so a drag keeps tracking when the finger leaves its bounds; capture releases after pointerup or pointercancel.

    Figure 1. A touch and who decides what it means

    sequenceDiagram accTitle: Who decides what a touch means accDescr: A finger touches a carousel. The page declares touch-action pan-y on the carousel, so the browser keeps vertical scrolling and sends horizontal movement to the page as pointer events. If the finger starts moving vertically the browser takes over, the page receives pointercancel, and its drag state is reset. participant F as Finger participant B as Browser participant P as Page (carousel) F->>B: touch down B->>P: pointerdown (touch-action pan-y) F->>B: moves sideways B->>P: pointermove (page drags) F->>B: starts moving up or down B->>B: this is a vertical pan, browser takes over B->>P: pointercancel P->>P: reset drag state

    How to read this: the declaration touch-action: pan-y is a division of labour agreed in advance. The browser does not wait for your code to decide on scroll, and your code is told when the browser claims the gesture.

    Figure 2. Choosing a touch-action for a region

    flowchart TD accTitle: Choosing a touch-action value for a region of the page accDescr: If the region has no custom gesture, leave touch-action auto. If it only needs faster taps, use manipulation. If it handles horizontal drags, use pan-y. If it handles drags in both directions such as a map or a canvas, use none and provide zoom controls and an alternative. S["A region of the page"] --> Q1{"Custom gesture
    in this region?"} Q1 -->|no| Q2{"Only need faster taps?"} Q2 -->|no| A["auto (default)"] Q2 -->|yes| M["manipulation"] Q1 -->|yes| Q3{"One axis only?"} Q3 -->|"horizontal"| Y["pan-y"] Q3 -->|"both"| N["none, plus zoom buttons
    and a non-drag alternative"]

    How to read this: pick the least restrictive value that still lets your code have the gesture. The further down the tree you go, the more of the browser's built-in behaviour (and accessibility) you take on yourself.

    Illustration 1: the minimal example, classifying a touch

    A gesture handler is a small function of recorded samples. This script classifies one pointer's samples as a tap, long press, swipe or browser takeover. The slop and long-press thresholds are illustrative values chosen for the demo, not platform constants. Run in Node:

    const TAP_SLOP = 10;       // px, illustrative
    const LONG_PRESS_MS = 500; // ms, illustrative
    function classify(samples) {
      const first = samples[0], last = samples.at(-1);
      if (last.type === "cancel") return "cancelled (the browser took over, reset your state)";
      const dx = last.x - first.x, dy = last.y - first.y;
      const dist = Math.hypot(dx, dy), dt = last.t - first.t;
      if (dist <= TAP_SLOP) return dt >= LONG_PRESS_MS ? "long press" : "tap";
      return Math.abs(dx) >= Math.abs(dy) ? `swipe ${dx > 0 ? "right" : "left"}` : `swipe ${dy > 0 ? "down" : "up"}`;
    }
    const s = (t, x, y, type) => ({ t, x, y, type });
    const cases = {
      "quick touch, tiny wobble": [s(0, 100, 100, "down"), s(8, 103, 101, "move"), s(90, 103, 101, "up")],
      "held still": [s(0, 100, 100, "down"), s(650, 100, 100, "up")],
      "flick left": [s(0, 200, 100, "down"), s(60, 120, 104, "move"), s(110, 60, 106, "up")],
      "drag down": [s(0, 100, 50, "down"), s(80, 102, 200, "up")],
      "browser started a scroll": [s(0, 100, 50, "down"), s(40, 100, 90, "move"), s(41, 100, 90, "cancel")],
    };
    for (const [name, samples] of Object.entries(cases)) console.log(name.padEnd(26), "->", classify(samples));

    Output, from running it in Node 26.13.1:

    quick touch, tiny wobble   -> tap
    held still                 -> long press
    flick left                 -> swipe left
    drag down                  -> swipe down
    browser started a scroll   -> cancelled (the browser took over, reset your state)

    The slop radius keeps a finger's wobble a tap; the last row is the case code forgets, and the one pointercancel reports.

    Viewport, keyboard and notches

    On a phone the visible area changes while the user scrolls and types. MDN defines vh as equivalent to lvh, the large viewport, and says svh is the small viewport (browser interface expanded) and dvh the dynamic one, which "can cause the content to resize while a user is scrolling a page". A full-screen panel sized with 100vh may therefore be partly covered when browser controls are shown; svh always fits, dvh fits exactly but resizes as controls appear.

    The on-screen keyboard has its own control. MDN documents interactive-widget in the viewport meta tag with three values: resizes-visual (the default, the visual viewport is resized), resizes-content and overlays-content. A fixed footer with an input is the case to test. For notches and rounded corners, viewport-fit=cover makes the viewport fill the display and MDN says it is "highly recommended" to use the safe-area variables so important content stays inside; env(safe-area-inset-bottom) is the value for a bottom bar.

    Target size, dragging and hover

    Fingers are bigger than cursors. WCAG 2.2 success criterion 2.5.8 (Level AA) requires pointer targets of at least 24 by 24 CSS pixels, with exceptions, the main one being spacing: an undersized target passes if a 24 CSS pixel circle centred on it does not intersect another target or another undersized target's circle. Success criterion 2.5.7 (Level AA) requires that all functionality that uses a dragging movement can be achieved by a single pointer without dragging, unless dragging is essential. The criterion covers content that implements its own scrolling or suppresses the browser's, so a custom carousel needs buttons or taps as well as swipe. Hover is a third trap: MDN says many mobile devices emulate hover with an inconvenient long tap, and @media (hover: hover) tests whether the primary input can hover. Put hover-only enhancements behind it and make the control available by tap and focus.

    Illustration 2: the realistic example, a cart row

    The ShopStream cart row has a minus button, a plus button and a remove icon. This script is a model of the 2.5.8 rule described above (boxes in CSS pixels), not an official checker. Run in Node:

    const MIN = 24, R = MIN / 2;
    const small = (t) => t.w < MIN || t.h < MIN;
    const centre = (t) => ({ x: t.x + t.w / 2, y: t.y + t.h / 2 });
    function circleHitsBox(c, b) {
      const nx = Math.max(b.x, Math.min(c.x, b.x + b.w));
      const ny = Math.max(b.y, Math.min(c.y, b.y + b.h));
      return Math.hypot(c.x - nx, c.y - ny) < R;
    }
    function check(targets) {
      return targets.map((t) => {
        if (!small(t)) return `${t.name}: ok, ${t.w}x${t.h} is at least ${MIN}x${MIN}`;
        const c = centre(t);
        const clash = targets.filter((o) => o !== t && (small(o)
          ? Math.hypot(centre(o).x - c.x, centre(o).y - c.y) < MIN
          : circleHitsBox(c, o)));
        return clash.length
          ? `${t.name}: FAIL, ${t.w}x${t.h} and its ${MIN}px circle meets ${clash.map((o) => o.name).join(", ")}`
          : `${t.name}: ok by spacing, ${t.w}x${t.h} with a clear ${MIN}px circle`;
      });
    }
    const rows = {
      "A: two 20px buttons, 2px apart": [{ name: "minus", x: 0, y: 0, w: 20, h: 20 }, { name: "plus", x: 22, y: 0, w: 20, h: 20 }],
      "B: two 20px buttons, 40px apart": [{ name: "minus", x: 0, y: 0, w: 20, h: 20 }, { name: "plus", x: 60, y: 0, w: 20, h: 20 }],
      "C: two 44px buttons": [{ name: "minus", x: 0, y: 0, w: 44, h: 44 }, { name: "plus", x: 48, y: 0, w: 44, h: 44 }],
      "D: a 20px icon beside a 44px button": [{ name: "info", x: 0, y: 12, w: 20, h: 20 }, { name: "buy", x: 24, y: 0, w: 44, h: 44 }],
    };
    for (const [name, ts] of Object.entries(rows)) console.log(name + "\n  " + check(ts).join("\n  "));

    Output, from running it in Node 26.13.1:

    A: two 20px buttons, 2px apart
      minus: FAIL, 20x20 and its 24px circle meets plus
      plus: FAIL, 20x20 and its 24px circle meets minus
    B: two 20px buttons, 40px apart
      minus: ok by spacing, 20x20 with a clear 24px circle
      plus: ok by spacing, 20x20 with a clear 24px circle
    C: two 44px buttons
      minus: ok, 44x44 is at least 24x24
      plus: ok, 44x44 is at least 24x24
    D: a 20px icon beside a 44px button
      info: ok by spacing, 20x20 with a clear 24px circle
      buy: ok, 44x44 is at least 24x24

    Row A is the typical stepper that mis-taps. Row C passes by size, and the 44 pixel figure is this lesson's example, not a cited requirement; WCAG's minimum is 24. Row D shows the spacing exception working for a small icon.

    The main thread is shared with the tap

    A tap's response time has three parts. web.dev's description of INP names them: input delay ("the time before any callback for an interaction is handled"), processing duration and presentation delay. It counts taps, clicks and key presses, and not scrolling or hovering. Its thresholds, at the 75th percentile of field page loads, split by mobile and desktop, are 200 ms or less for good, above 500 ms for poor. Any long task on the main thread, which web.dev defines as a task over 50 ms, can land in front of a tap and make the input delay long.

    Figure 3. Where a tap's time goes

    The three phases of a tap's responseTap to Main thread busy?; Main thread busy? to Your handlers (waits); Your handlers to Next frame (renders)Tap: touch inputTaptouch inputMain thread busy?: input delayMain threadbusy?input delayYour handlers: processingYour handlersprocessingNext frame: presentationNext framepresentationwaitsrenders

    How to read this: the three boxes after the tap are the three phases named in the web.dev INP article. A long task before the handler grows the first, heavy handlers grow the second and expensive rendering grows the third.

    The fix for the first phase is yielding. web.dev says splitting work lets "the browser respond to higher-priority work much sooner", and that scheduler.yield() lets the continuation run before other queued tasks, but that at the time of the article it was supported in Chrome 129, Edge 129 and Firefox 142 and not Safari, so a setTimeout fallback is needed. The same page says it no longer recommends isInputPending(). For the second and third phases, the INP optimisation guide recommends doing only the work needed for the next frame first, avoiding layout thrashing, keeping the DOM small and considering content-visibility.

    Illustration 3: a failure, the tap stuck behind a long task

    A tap arrives just after a six-chunk job starts. This script orders the work and the tap handler in the event loop with and without yielding; it shows ordering, not durations. Run in Node:

    const log = [];
    const chunks = 6;
    function runJob(yieldBetween) {
      return new Promise((resolve) => {
        let i = 0;
        const step = () => {
          log.push(`work ${++i}/${chunks}`);
          if (i === chunks) return resolve();
          if (yieldBetween) setTimeout(step, 0); else step();
        };
        step();
      });
    }
    async function scenario(label, yieldBetween) {
      log.length = 0;
      const job = runJob(yieldBetween);
      setTimeout(() => log.push("TAP handler runs"), 0); // a tap queued just after the job starts
      await job;
      await new Promise((r) => setTimeout(r, 5));
      console.log(label + "\n  " + log.join(" | "));
    }
    await scenario("one long task (no yielding)", false);
    await scenario("chunks with setTimeout yields", true);

    Output, from running it in Node 26.13.1:

    one long task (no yielding)
      work 1/6 | work 2/6 | work 3/6 | work 4/6 | work 5/6 | work 6/6 | TAP handler runs
    chunks with setTimeout yields
      work 1/6 | work 2/6 | TAP handler runs | work 3/6 | work 4/6 | work 5/6 | work 6/6

    Without yielding, the tap waits for the whole job. With yields, it runs between chunks. Chunk length and real durations must be measured on the phone itself; this lesson shows the order, not milliseconds.

    Reading mobile data without inventing numbers

    Phones vary widely in CPU, memory and network. The practical rule is to segment field data by device class and connection and set budgets from your own percentiles; see performance budgets and profiling. MDN's page on the Network Information API shows effectiveType as an estimate of connection speed and carries a "limited availability" banner, so code that adapts to it must work when it is absent.

    Trade-offs

    Choice Gain Cost Wrong when
    touch-action: manipulation Taps without double-tap-zoom delay, pinch zoom kept No double-tap zoom on that region The region is long text people zoom into
    touch-action: none Page owns every gesture Browser pan and zoom lost, accessibility risk A normal scrolling page
    passive: true listeners Scrolling starts at once preventDefault() does nothing The handler must cancel scroll
    dvh Exact fit as controls move Layout can resize while scrolling Content must not move
    Large targets Fewer mis-taps Less content per screen A dense table where spacing already passes

    Build it

    This lesson has no lab. The three Node scripts above are teaching models with no repository folder and no golden file, and nothing here was run on a touch device or in a touch browser.

    In practice: the ShopStream product page on a phone

    This is a realistic scenario, not a case history. It is a composite built from common patterns, and every number is an illustrative assumption.

    The situation

    On phones, shoppers say the product page "fights" them: swiping the photo carousel sometimes scrolls the page instead, the quantity stepper is hard to hit, and the add-to-cart button feels slow just after load. Field data (not shown here) puts the slow interactions on mid-range phones.

    Starting architecture

    Starting architecture: a product page on a phonePhoto carousel to Main thread; Quantity stepper to Main thread; Main thread to ShopStream API (HTTPS)Photo carousel: swipe handlersPhoto carouselswipe handlersQuantity stepper: small buttonsQuantitysteppersmall buttonsMain thread: startup scriptsMain threadstartup scriptsShopStream APIShopStream APIHTTPS

    Options considered

    Option Gain Cost Wrong when
    A. Fix only the scripts Shorter long tasks The carousel still fights the page Gestures are the main complaint
    B. Declare gestures and resize targets, then chunk startup work Addresses all three complaints Several small changes to test Time allows only one change
    C. Replace the carousel with native scroll snapping Browser-owned scrolling Less custom behaviour The design needs custom dragging

    The decision

    Option B, in this order: set touch-action: pan-y on the carousel and reset state on pointercancel; give the stepper buttons larger targets and spacing; add previous and next buttons to the carousel so no swipe is required; yield between chunks of startup work. This is one defensible answer, not a rule.

    Rollout and verification

    Ship behind a flag to a share of phone traffic (illustrative: 10 percent). Compare field interaction latency between flag groups at the same percentile, and check each change by hand on a real device, which this lesson could not do: a slow vertical drag on the carousel, the stepper with a thumb, and a first tap during load.

    The 2 a.m. failure

    After the release, a carousel photo sometimes sticks to the finger and follows it after release on one phone model.

    First checks: whether pointercancel is handled and releases the drag; whether capture is released on both; whether a reproduction needs a particular browser version. Mitigation: end the drag on pointerup and pointercancel alike and release capture there, and turn the flag off if it spreads. Follow-up: add a gesture test that sends a cancel in the middle of a drag.

    Architect's notes

    • Declare gestures in CSS first. The browser can decide without waiting for scripts.
    • Every drag has a non-drag path.
    • Handle cancel as a normal end, with one cleanup function for up and cancel.
    • Budget the main thread, not only bytes.
    • Test on real devices and in field data.

    Common mistakes

    • Disabling zoom with user-scalable=no to remove tap delay.
    • Using touch-action: none on a whole page.
    • Ignoring pointercancel, leaving a drag stuck.
    • Sizing full-screen panels with vh.
    • Relying on hover for essential controls.

    Key takeaways

    • The browser arbitrates touch; declare your gestures with touch-action and handle pointercancel.
    • Passive listeners let scrolling start without waiting for your code.
    • Viewport units, the keyboard and safe areas each have a setting; choose them on purpose.
    • WCAG 2.2 asks for 24 CSS pixel targets (or spacing) and a no-drag alternative.
    • Yield so a tap is not stuck behind a long task, and measure on real phones.

    Practice exercises

    Exercise 1 (30 min). Add a double tap result to the Illustration 1 script by tracking two taps within a window you choose. What state does it need between gestures?

    Exercise 2 (1 hour). Take a real page of yours, list every interactive target under 24 CSS pixels, and decide for each whether size, spacing or an equivalent control makes it pass.

    Exercise 3 (half day). Design a swipe-to-delete row and write its non-drag alternative. Which touch-action does it need?

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments