惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
T
Troy Hunt's Blog
P
Proofpoint News Feed
H
Help Net Security
博客园 - 叶小钗
N
Netflix TechBlog - Medium
F
Full Disclosure
Vercel News
Vercel News
C
Cyber Attacks, Cyber Crime and Cyber Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
GbyAI
GbyAI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 【当耐特】
Martin Fowler
Martin Fowler
V
V2EX
Latest news
Latest news
L
LangChain Blog
The Register - Security
The Register - Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Schneier on Security
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
News and Events Feed by Topic
M
MIT News - Artificial intelligence
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
The Exploit Database - CXSecurity.com
Microsoft Security Blog
Microsoft Security Blog
S
Secure Thoughts
A
About on SuperTechFans
人人都是产品经理
人人都是产品经理
T
The Blog of Author Tim Ferriss
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Spread Privacy
Spread Privacy
S
Securelist
Forbes - Security
Forbes - Security
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Last Week in AI
Last Week in AI
T
Threat Research - Cisco Blogs
V
Vulnerabilities – Threatpost
MyScale Blog
MyScale Blog
G
Google Developers Blog
L
Lohrmann on Cybersecurity
博客园 - Franky
T
Tor Project blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
V
Visual Studio Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
Y
Y Combinator Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How I Got MediaPipe Face Landmarker Running in the Browser with Zero Build Tools (And the Import Bug That Wasted My Week)
Khan · 2026-04-30 · via DEV Community

I built facecalculators.com a free, privacy-first face shape detector that runs entirely in the browser. No uploads. No server. No account. All facial analysis happens locally via WebAssembly, and nothing biometric ever leaves the device.

The core of it is Google's MediaPipe Face Landmarker with the 478-point 3D model. Getting it working in a pure vanilla JavaScript environment, without a build tool, without React, and inside a WordPress theme, was not as straightforward as the docs make it look. This article documents every failure mode I hit and the exact solution that finally worked.

If you are building anything with MediaPipe in the browser and not using a bundler, this will save you real hours.

What the Docs Tell You vs. What Actually Works

The official Google documentation shows two ways to load the library via CDN.

Option A (script tag):

<script src="https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision/vision_bundle.mjs"
  crossorigin="anonymous"></script>

Enter fullscreen mode Exit fullscreen mode

Option B (dynamic import inside a module):

const { FaceLandmarker, FilesetResolver } =
  await import("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision");

Enter fullscreen mode Exit fullscreen mode

Both of these fail in specific and frustrating ways if you are not using a bundler.

Failure 1: The /wasm/index.js Path

A lot of older tutorials and Stack Overflow answers use this pattern for the FilesetResolver:

const vision = await FilesetResolver.forVisionTasks(
  "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm/index.js"
);

Enter fullscreen mode Exit fullscreen mode

This will silently fail in certain environments. The path resolves but the WASM runtime does not initialize correctly. You get no error. The landmarker just never loads. Camera permissions fire, the video stream starts, and then nothing comes back from detectForVideo().

The correct path drops the filename entirely:

const vision = await FilesetResolver.forVisionTasks(
  "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm"
);

Enter fullscreen mode Exit fullscreen mode

That trailing directory path lets jsDelivr resolve the correct entry point. This alone fixed what looked like a camera failure but was actually a model initialization failure.

Failure 2: vision_bundle.mjs and the Default Export Problem

The docs also suggest vision_bundle.mjs as a script tag source. If you then try to use it as an ES module import, you will get an error because vision_bundle.mjs uses a default export.

// This fails with a module import error
import { FaceLandmarker, FilesetResolver } from
  "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision/vision_bundle.mjs";

Enter fullscreen mode Exit fullscreen mode

The named exports you need (FaceLandmarker, FilesetResolver, DrawingUtils) are not directly available through that path when you import it as a module.

The correct approach is to import from the package root, which jsDelivr resolves to the proper entry point:

const {
  FaceLandmarker,
  FilesetResolver,
  DrawingUtils
} = await import("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.14");

Enter fullscreen mode Exit fullscreen mode

Note the pinned version number. Using @latest works but can break if Google pushes a breaking change. Pin your version in production.

Failure 3: WordPress and type="module"

If you are loading your JavaScript inside WordPress and your script is not tagged as type="module", dynamic import() calls will fail silently in some browsers.

In your functions.php , enqueue the script with the module attribute:

function fc_enqueue_calculator_scripts() {
  if ( is_page_template( 'page-calculator.php' ) ) {
    wp_enqueue_script(
      'fc-calculator',
      get_stylesheet_directory_uri() . '/assets/js/calculator.js',
      [],
      '1.0.0',
      true
    );
    // Force type="module" on the script tag
    add_filter( 'script_loader_tag', function( $tag, $handle ) {
      if ( $handle === 'fc-calculator' ) {
        return str_replace( ' src=', ' type="module" src=', $tag );
      }
      return $tag;
    }, 10, 2 );
  }
}
add_action( 'wp_enqueue_scripts', 'fc_enqueue_calculator_scripts' );

Enter fullscreen mode Exit fullscreen mode

Without type="module", the browser treats your JS file as a classic script. Dynamic imports work technically, but the module scope isolation breaks the way MediaPipe resolves its internal WASM paths, causing initialization to fail or behave inconsistently across browsers.

The Working Import Pattern

Here is the complete initialization sequence that works reliably in a vanilla JS ES module without any build step:

const FC_MP_CDN = "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.14";
const FC_MODEL_URL =
  "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task";

let fcLandmarker = null;

async function fcLoadMediaPipe() {
  const vision = await import(FC_MP_CDN);
  const { FaceLandmarker, FilesetResolver } = vision;

  const filesetResolver = await FilesetResolver.forVisionTasks(
    `${FC_MP_CDN}/wasm`
  );

  fcLandmarker = await FaceLandmarker.createFromOptions(filesetResolver, {
    baseOptions: {
      modelAssetPath: FC_MODEL_URL,
      delegate: "GPU"
    },
    runningMode: "VIDEO",
    numFaces: 1
  });

  return fcLandmarker;
}

Enter fullscreen mode Exit fullscreen mode

That is the entire initialization. No npm. No webpack. No node_modules. Runs straight in the browser.

VIDEO Mode and IMAGE Mode on the Same Landmarker Instance

This is the part that no tutorial covers, because most tutorials only implement one analysis method.

On facecalculators.com, there are three input modes: live camera (VIDEO), photo upload (IMAGE), and manual measurements. The camera and photo upload both use the same fcLandmarker instance. Switching between them requires calling setOptions() to change the running mode.

If you do not do this, calling detect() on a VIDEO-mode landmarker throws an error, and calling detectForVideo() on an IMAGE-mode landmarker also throws an error.

// Camera (VIDEO) detection loop
function fcCameraDetectLoop(videoEl) {
  if (!fcLandmarker) return;
  const timestamp = performance.now();
  const result = fcLandmarker.detectForVideo(videoEl, timestamp);
  processLandmarkResult(result);
  requestAnimationFrame(() => fcCameraDetectLoop(videoEl));
}

// Photo upload (IMAGE) analysis
async function fcAnalyzePhoto(imageEl) {
  if (!fcLandmarker) return null;

  // Switch the shared instance to IMAGE mode
  await fcLandmarker.setOptions({ runningMode: "IMAGE" });

  const result = fcLandmarker.detect(imageEl);

  // Switch back to VIDEO mode for the camera to work again
  await fcLandmarker.setOptions({ runningMode: "VIDEO" });

  return result;
}

Enter fullscreen mode Exit fullscreen mode

The setOptions() call is async and takes a moment. Do not call detect() before await setOptions() resolves or you will get a running mode conflict error.

Stealth Preloading with Intersection Observer

The MediaPipe WASM runtime is around 6MB. If you initialize it on page load, it blocks visible page rendering on slower connections. If you wait for the user to click the camera button, there is a noticeable delay between tap and camera opening.

The solution is intersection observer based preloading. The landmarker starts downloading as soon as the detect button enters the viewport, which is effectively instant on most pages since the button is above the fold. By the time the user reads the page and decides to tap, the model is already loaded.

function fcStealthPreload() {
  const detectBtn = document.getElementById('fc-detect-btn');
  if (!detectBtn) return;

  const observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      fcLoadMediaPipe(); // Fire and forget populates fcLandmarker when ready
      observer.disconnect();
    }
  }, { threshold: 0.1 });

  observer.observe(detectBtn);
}

// Also trigger on full page load as a backup
window.addEventListener('load', () => {
  if (!fcLandmarker) fcLoadMediaPipe();
});

// Start observing once DOM is ready
document.addEventListener('DOMContentLoaded', fcStealthPreload);

Enter fullscreen mode Exit fullscreen mode

On a fast connection, MediaPipe is initialized before the user ever taps. On a slow connection, the camera opens and shows a brief loading state while the model finishes. Either way, the perceived performance is dramatically better than loading on tap.

The 478-Point Model vs. The Old 468-Point Mesh

Most tutorials still reference the old MediaPipe Face Mesh solution, which outputs 468 landmarks. The current Face Landmarker outputs 478 landmarks, with the 10 additional points covering the iris region.

For face shape classification, the iris landmarks are useful for measuring eye distance accurately, which is a key input for alignment detection (confirming the user is centered before capture). The outer iris boundary gives a more stable eye width measurement than guessing from the surrounding mesh points.

The model file for the 478-point landmarker is:

https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task

Enter fullscreen mode Exit fullscreen mode

The older face mesh CDN paths from tutorials dated before 2023 point to deprecated models. If your tutorial uses @mediapipe/face_mesh as the npm package name rather than @mediapipe/tasks-vision, it is targeting the legacy solution.

Landmark Indices for Geometric Measurements

For a face shape classifier, the landmarks you care most about are structural, not expressive. These are the indices used in facecalculators.com for the primary measurements:

// Approximate landmark index references for geometric analysis
// These are stable across most detection results

const FC_LANDMARKS = {
  // Face width at cheekbones (approximately)
  LEFT_CHEEK:     234,
  RIGHT_CHEEK:    454,

  // Forehead width
  LEFT_FOREHEAD:  71,
  RIGHT_FOREHEAD: 301,

  // Jawline width
  LEFT_JAW:       132,
  RIGHT_JAW:      361,

  // Chin tip
  CHIN:           152,

  // Top of forehead hairline region
  TOP_HEAD:       10,

  // Key eye landmarks for alignment detection
  LEFT_EYE_OUTER:  33,
  RIGHT_EYE_OUTER: 263,
};

function fcMeasureWidth(landmarks, leftIndex, rightIndex) {
  const left  = landmarks[leftIndex];
  const right = landmarks[rightIndex];
  return Math.abs(left.x - right.x);
}

function fcMeasureHeight(landmarks, topIndex, bottomIndex) {
  const top    = landmarks[topIndex];
  const bottom = landmarks[bottomIndex];
  return Math.abs(top.y - bottom.y);
}

Enter fullscreen mode Exit fullscreen mode

The landmark coordinates are normalized to the range 0.0 to 1.0 relative to the image dimensions. For ratio calculations (face length divided by cheekbone width, etc.), the normalization cancels out, so you do not need to convert to pixel values unless you are drawing on a canvas.

Alignment Detection Before Capture

One thing that significantly improves classification accuracy is only capturing when the face is reasonably centered and forward-facing. A face turned 20 degrees sideways will produce wrong measurements for a face shape classifier.

Three checks before enabling capture:

function fcCheckAlignment(landmarks) {
  const leftEye  = landmarks[FC_LANDMARKS.LEFT_EYE_OUTER];
  const rightEye = landmarks[FC_LANDMARKS.RIGHT_EYE_OUTER];

  // 1. Eye distance check - face must be close enough to fill the frame
  const eyeDistance = Math.abs(leftEye.x - rightEye.x);
  const eyeDistanceOk = eyeDistance > 0.25;

  // 2. Horizontal rotation - eyes should be at similar Y positions
  const eyeYDiff = Math.abs(leftEye.y - rightEye.y);
  const rotationOk = eyeYDiff < 0.05;

  // 3. Vertical tilt - nose tip should be between eyes vertically
  const noseTip = landmarks[1];
  const eyeMidY = (leftEye.y + rightEye.y) / 2;
  const tiltOk  = Math.abs(noseTip.y - eyeMidY) < 0.15;

  return eyeDistanceOk && rotationOk && tiltOk;
}

Enter fullscreen mode Exit fullscreen mode

When all three pass with 90%+ overall detection confidence, the UI unlocks the capture button. This is the pattern used in the live camera mode on facecalculators.com and it virtually eliminates bad captures.

What I Learned

The documentation gap around no-build-tool MediaPipe setups in the browser is real. Most resources assume npm and a bundler. The combination of:

  • Importing from the jsDelivr package root (not /wasm/index.js)
  • Using type="module" on the script tag
  • Switching runningMode via setOptions() when sharing one landmarker across VIDEO and IMAGE inputs
  • Preloading via IntersectionObserver instead of on-demand

...is not documented anywhere as a complete pattern. Hopefully this saves someone the week of debugging it cost me.

The live implementation is at facecalculators.com - completely free, no account needed. If you want to see the alignment lock, the X-Ray scan, and the Polaroid result card in action, open it on your phone.

Happy to answer questions in the comments about any of the implementation details above.