webf-async-rendering

1
0
Source

Understand and work with WebF's async rendering model - handle onscreen/offscreen events and element measurements correctly. Use when getBoundingClientRect returns zeros, computed styles are incorrect, measurements fail, or elements don't layout as expected.

Install

mkdir -p .claude/skills/webf-async-rendering && curl -L -o skill.zip "https://mcp.directory/api/skills/download/3788" && unzip -o skill.zip -d .claude/skills/webf-async-rendering && rm skill.zip

Installs to .claude/skills/webf-async-rendering

About this skill

WebF Async Rendering

Note: WebF development is nearly identical to web development - you use the same tools (Vite, npm, Vitest), same frameworks (React, Vue, Svelte), and same deployment services (Vercel, Netlify). This skill covers one of the 3 key differences: WebF's async rendering model. The other two differences are API compatibility and routing.

This is the #1 most important concept to understand when moving from browser development to WebF.

The Fundamental Difference

In Browsers (Synchronous Layout)

When you modify the DOM, the browser immediately performs layout calculations:

// Browser behavior
const div = document.createElement('div');
document.body.appendChild(div);
console.log(div.getBoundingClientRect()); // ✅ Returns real dimensions

Layout happens synchronously - you get dimensions right away, but this can cause performance issues (layout thrashing).

In WebF (Asynchronous Layout)

When you modify the DOM, WebF batches the changes and processes them in the next rendering frame:

// WebF behavior
const div = document.createElement('div');
document.body.appendChild(div);
console.log(div.getBoundingClientRect()); // ❌ Returns zeros! Not laid out yet.

Layout happens asynchronously - elements exist in the DOM tree but haven't been measured/positioned yet.

Why Async Rendering?

Performance: WebF's async rendering is 20x cheaper than browser synchronous layout!

  • DOM updates are batched together
  • Multiple changes processed in one optimized pass
  • Eliminates layout thrashing
  • No need for DocumentFragment optimizations

Trade-off: You must explicitly wait for layout to complete before measuring elements.

The Solution: onscreen/offscreen Events

WebF provides two non-standard events to handle the async lifecycle:

EventWhen It FiresPurpose
onscreenElement has been laid out and renderedSafe to measure dimensions, get computed styles
offscreenElement removed from render treeCleanup and resource management

Think of these like IntersectionObserver but for layout lifecycle, not viewport visibility.

How to Measure Elements Correctly

❌ WRONG: Measuring Immediately

// DON'T DO THIS - Will return 0 or incorrect values
const div = document.createElement('div');
div.textContent = 'Hello WebF';
document.body.appendChild(div);

const rect = div.getBoundingClientRect();  // ❌ Returns zeros!
console.log(rect.width);  // 0
console.log(rect.height); // 0

✅ CORRECT: Wait for onscreen Event

// DO THIS - Wait for layout to complete
const div = document.createElement('div');
div.textContent = 'Hello WebF';

div.addEventListener('onscreen', () => {
  // Element is now laid out - safe to measure!
  const rect = div.getBoundingClientRect();  // ✅ Real dimensions
  console.log(`Width: ${rect.width}, Height: ${rect.height}`);
});

document.body.appendChild(div);

React: useFlutterAttached Hook

For React developers, WebF provides a convenient hook:

❌ WRONG: Using useEffect

import { useEffect, useRef } from 'react';

function MyComponent() {
  const ref = useRef(null);

  useEffect(() => {
    // ❌ Element not laid out yet!
    const rect = ref.current.getBoundingClientRect();
    console.log(rect); // Will be zeros
  }, []);

  return <div ref={ref}>Content</div>;
}

✅ CORRECT: Using useFlutterAttached

import { useFlutterAttached } from '@openwebf/react-core-ui';

function MyComponent() {
  const ref = useFlutterAttached(
    () => {
      // ✅ onAttached callback - element is laid out!
      const rect = ref.current.getBoundingClientRect();
      console.log(`Width: ${rect.width}, Height: ${rect.height}`);
    },
    () => {
      // onDetached callback (optional)
      console.log('Component removed from render tree');
    }
  );

  return <div ref={ref}>Content</div>;
}

Layout-Dependent APIs

Only call these inside onscreen callback or useFlutterAttached:

  • element.getBoundingClientRect()
  • window.getComputedStyle(element)
  • element.offsetWidth / element.offsetHeight
  • element.clientWidth / element.clientHeight
  • element.scrollWidth / element.scrollHeight
  • element.offsetTop / element.offsetLeft
  • Any logic that depends on element position or size

Common Scenarios

Scenario 1: Measuring After Style Changes

const div = document.getElementById('myDiv');

// ❌ WRONG
div.style.width = '500px';
const rect = div.getBoundingClientRect(); // Old dimensions!

// ✅ CORRECT
div.style.width = '500px';
div.addEventListener('onscreen', () => {
  const rect = div.getBoundingClientRect(); // New dimensions!
}, { once: true }); // Use 'once' to remove listener after first call

Scenario 2: Positioning Tooltips/Popovers

function showTooltip(targetElement) {
  const tooltip = document.createElement('div');
  tooltip.className = 'tooltip';
  tooltip.textContent = 'Tooltip text';

  tooltip.addEventListener('onscreen', () => {
    // Now we can safely position the tooltip
    const targetRect = targetElement.getBoundingClientRect();
    const tooltipRect = tooltip.getBoundingClientRect();

    tooltip.style.left = `${targetRect.left}px`;
    tooltip.style.top = `${targetRect.bottom + 5}px`;
  }, { once: true });

  document.body.appendChild(tooltip);
}

Scenario 3: React Component with Measurement

import { useFlutterAttached } from '@openwebf/react-core-ui';
import { useState } from 'react';

function MeasuredBox() {
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });

  const ref = useFlutterAttached(() => {
    const rect = ref.current.getBoundingClientRect();
    setDimensions({
      width: rect.width,
      height: rect.height
    });
  });

  return (
    <div ref={ref} style={{ padding: '20px', border: '1px solid' }}>
      <p>This box is {dimensions.width}px wide</p>
      <p>and {dimensions.height}px tall</p>
    </div>
  );
}

Performance Benefits

WebF's async rendering provides significant advantages:

  1. Batched Updates: Multiple DOM changes processed together
  2. No Layout Thrashing: Eliminates read-write-read-write patterns
  3. Optimized Rendering: Single pass through the render tree
  4. No DocumentFragment Needed: Batching is automatic

Compare to browsers where you'd need to carefully batch operations:

// Browser optimization (not needed in WebF!)
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
  const div = document.createElement('div');
  fragment.appendChild(div);
}
document.body.appendChild(fragment); // Single layout

In WebF, just append directly - it's automatically optimized!

Common Mistakes

Mistake 1: Forgetting to Wait

// ❌ WRONG
const div = document.createElement('div');
document.body.appendChild(div);
initializeWidget(div); // Assumes div is laid out - will fail!
// ✅ CORRECT
const div = document.createElement('div');
div.addEventListener('onscreen', () => {
  initializeWidget(div); // Now it's safe!
}, { once: true });
document.body.appendChild(div);

Mistake 2: Not Cleaning Up Listeners

// ❌ WRONG - Memory leak
element.addEventListener('onscreen', handleLayout);
// Listener never removed!

// ✅ CORRECT
element.addEventListener('onscreen', handleLayout, { once: true });
// OR
element.addEventListener('onscreen', handleLayout);
// Later...
element.removeEventListener('onscreen', handleLayout);

Mistake 3: Using IntersectionObserver for Layout

// ❌ WRONG - IntersectionObserver is for viewport visibility, not layout
const observer = new IntersectionObserver((entries) => {
  // This fires based on viewport, not layout completion!
});

// ✅ CORRECT - Use onscreen for layout lifecycle
element.addEventListener('onscreen', () => {
  // Element is laid out
});

Debugging Tips

If you're getting zero or incorrect dimensions:

  1. Check if you're waiting for onscreen: Most common issue
  2. Verify element is actually added to DOM: Must be in document tree
  3. Confirm element has display style: display: none elements don't layout
  4. Use console.log in onscreen callback: Verify callback fires
element.addEventListener('onscreen', () => {
  console.log('✅ onscreen fired');
  console.log(element.getBoundingClientRect());
}, { once: true });

Resources

Key Takeaways

DO:

  • Use onscreen event or useFlutterAttached hook
  • Wait for layout before measuring elements
  • Use { once: true } for one-time measurements

DON'T:

  • Measure immediately after appendChild()
  • Rely on synchronous layout like browsers
  • Use IntersectionObserver for layout detection
  • Forget to clean up event listeners

webf-native-plugins

openwebf

Install WebF native plugins to access platform capabilities like sharing, payment, camera, geolocation, and more. Use when building features that require native device APIs beyond standard web APIs.

20

webf-routing-setup

openwebf

Setup hybrid routing with native screen transitions in WebF - configure navigation using WebF routing instead of SPA routing. Use when setting up navigation, implementing multi-screen apps, or when react-router-dom/vue-router doesn't work as expected.

00

webf-api-compatibility

openwebf

Check Web API and CSS feature compatibility in WebF - determine what JavaScript APIs, DOM methods, CSS properties, and layout modes are supported. Use when planning features, debugging why APIs don't work, or finding alternatives for unsupported features like IndexedDB, WebGL, float layout, or CSS Grid.

00

webf-native-ui-dev

openwebf

Develop custom native UI libraries based on Flutter widgets for WebF. Create reusable component libraries that wrap Flutter widgets as web-accessible custom elements. Use when building UI libraries, wrapping Flutter packages, or creating native component systems.

00

webf-infinite-scrolling

openwebf

Create high-performance infinite scrolling lists with pull-to-refresh and load-more capabilities using WebFListView. Use when building feed-style UIs, product catalogs, chat messages, or any scrollable list that needs optimal performance with large datasets.

50

webf-quickstart

openwebf

Get started with WebF development - setup WebF Go, create a React/Vue/Svelte project with Vite, and load your first app. Use when starting a new WebF project, onboarding new developers, or setting up development environment.

40

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318399

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

340397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

452339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.