Use the browser's built-in JavaScript APIs instead of libraries and legacy hacks. See which native APIs replace common workarounds, how to keep pages responsive to taps and clicks, and when HTML and CSS can do the job instead, then try each pattern live on this page.
JavaScript & Web APIs
87
Indexed platform features in the JavaScript & APIs tier, alongside 38 HTML & DOM features across 200+ expert-vetted guides.
Main-thread task budget
50 ms
Split any JavaScript task that runs longer than 50 milliseconds so the browser can handle clicks and taps in between.
Widely available threshold
30 mo
Time after a feature reaches every core browser before it counts as Widely available, Modern Web Guidance's default target.
Visual explanation & interactive model
How Baseline determines your JavaScript strategy
Before writing a single line of JavaScript, Modern Web Guidance checks Baseline (defined by the W3C WebDX Community Group) to decide whether a native API works everywhere out of the box or needs progressive enhancement. Select a project target below to see how recommendations change.
Limited availabilityNot yet in all core browsers
Supported in one or more browsers, not all. Requires a fallback or feature check before use.
Newly availableInteroperable across core browsers
Works in the latest version of every core browser. Some visitors may still be on older versions, so add a feature check.
Widely available30 months interoperable
Default target for Modern Web Guidance. Safe for most sites with zero polyfills or fallbacks.
By default, Modern Web Guidance assumes features in Baseline Widely available need no fallbacks. To allow newer features, you set a different Baseline target in your project's AGENTS.md file.
// Target: Baseline Widely available
// Safe to use directly without a polyfill or JSON hack:
const copy = structuredClone(userState);
Section 01 / Core philosophy
Why default JavaScript patterns often fall short
Language models and older tutorials were trained on years of historical repositories built to work around Internet Explorer 11. Left unguided, developers and AI agents repeat bloated workarounds instead of using what browsers now build in natively.
Principle 01
Prefer native APIs over library bloat
Historically, teams installed large utility packages for deep cloning, date arithmetic, grouping arrays or building tooltips. Modern browsers include native standards that run faster, ship zero extra bytes and stay maintained by browser engineers.
Principle 02
Reach for HTML and CSS first
Modern Web Guidance actively steers code away from JavaScript when HTML or CSS handles the interaction natively. Modals, popovers, accordions and sibling-count layouts perform better and preserve accessibility without bespoke scripts.
Principle 03
Protect the main thread
A fast page load means little if clicks freeze afterwards. By splitting tasks longer than 50 ms, scheduling work by priority and pausing rendering work while it is off screen, JavaScript cooperates with the browser rather than blocking user input.
Principle 04
Responsible, targeted fallbacks
When supporting older browsers or using newer features, avoid loading heavy global polyfills for every visitor. Use feature detection and conditional-async-dependencies to load a fallback only when the browser genuinely lacks the API.
How Modern Web Guidance delivers rules at coding timeCLI & offline index
Offline search & retrieval
Modern Web Guidance 1.0 (released 10 November 2026) finds the right guide locally, using an offline embedding model and BM25 search with no API calls or keys, then retrieves it into the agent's context. It covers 269 web features and 206 real-world use cases.
The legacy-scan command scans a project's HTML, CSS, JavaScript and framework files for legacy patterns that have a modern replacement. It covers the guides that have deterministic detection rules, about 20% of the catalogue. Modern Web Guidance can also be paired with Chrome DevTools for agents, so generated code can be checked in a live browser.
npx modern-web-guidance@latest legacy-scan .
Section 02 / Performance & INP
Break up any task longer than 50 milliseconds
Interaction to Next Paint (INP) measures how quickly a page responds when a user clicks, taps or types. Modern Web Guidance treats keeping the main thread free for input as a core rule rather than an optional afterthought.
Interactive simulation
Main-thread task chunking: Unguided vs Modern Web Guidance
Choose a JavaScript scheduling strategy below, click Run 180 ms workload and then click Simulate user tap while it runs to see how long the tap waits and when the work finishes. The timings are illustrative.
Ready
Main-thread execution timeline (visual scale)
Select a strategy and start the workload to inspect task slices.
Longest blocking slice
180 ms
Tap wait (affects INP)
Waiting…
Guidance verdict
Exceeds 50 ms
Fallback onlyWhy setTimeout(..., 0) comes second
Yielding with setTimeout(fn, 0) does let the browser handle a waiting tap, but it sends the rest of your work to the back of the task queue, behind other timers and tasks already waiting, so the job finishes later. Modern Web Guidance uses it only as the fallback for browsers without scheduler.yield().
Recommended patternscheduler.yield() with Promise fallback
Yielding with await scheduler.yield() lets pending input be handled, then resumes your work at the front of the queue, ahead of other tasks. The Scheduler API has Limited availability (not yet in every core browser), so feature-detect it with a setTimeout fallback. Use scheduler.postTask() to give separate pieces of work explicit priorities.
Mandatory performance constraints
Speculation rules, image priority and scroll discipline
Speculation Rules API restrictions: Use JSON-based <script type="speculationrules"> to prefetch or prerender likely next navigations instead of generic asset preloads. However, Modern Web Guidance says not to use speculation rules in Single-Page Applications (SPAs), and never to speculate URLs that change state, such as /logout or /add-to-cart. Speculation rules have Limited availability, so browsers without them simply ignore the rules.
Fetch priority interaction: Never put loading="lazy" on the Largest Contentful Paint (LCP) image; give it fetchpriority="high" instead. Don't add fetchpriority="low" to ordinary below-the-fold lazy images either. Keep low priority for images that are on screen but hidden, such as carousel slides, and for background fetches.
Scroll-end & off-screen pausing: Defer DOM updates, analytics and layout work until scrolling finishes (defer-work-until-scroll-ends). For rendering-heavy work such as <canvas> or WebGL loops, set content-visibility: auto and pause on the contentvisibilityautostatechange event when the browser skips rendering (efficient-background-processing). Keep IntersectionObserver for logic tied to exact visibility, such as infinite scroll.
Telemetry & page visibility
Observing real sessions cleanly
Initial visibility state: Scripts loaded asynchronously may run after a user switches tabs. Check visibility state reliably rather than assuming the page opened in the foreground.
Full-session analytics & fetchLater(): Batch telemetry events and schedule delivery on page exit without blocking unload using fetchLater() alongside the Page Visibility API. fetchLater() isn't in every browser yet, so feature-detect it and keep a fallback.
Diagnostics: Track Long animation frames (LoAF) to pinpoint which scripts block rendering, plus Event timing and Soft navigation performance entries for SPA transitions.
Section 03 / Modern JavaScript & APIs
Native primitives that replace third-party utility bloat
Across its 87 JavaScript & API features, Modern Web Guidance replaces error-prone legacy idioms and heavy utility packages with clean, built-in language and platform APIs.
Practical examples & live execution
Interactive legacy-to-modern JavaScript workbench
Pick an everyday coding task below to compare the unguided pattern against Modern Web Guidance, read why the upgrade matters and run the modern code directly in your browser.
Unguided / legacy pattern
Modern Web Guidance
Click to execute in your browser
Live execution output
Output will appear here after running the example.
Replaces mutable Date quirks, timezone drift bugs and bulky third-party calendar libraries across five dedicated MWG guides. Temporal still has Limited availability, so load a polyfill only where it's missing.
Handles text encoding, clipboard access and compiled C/C++ workloads natively, without custom libraries.
Section 04 / Architecture discipline
Use HTML and CSS before reaching for JavaScript
Custom JavaScript overlays, scroll listeners and positioning scripts frequently introduce memory leaks, layer collisions and broken keyboard focus. Modern Web Guidance insists on native HTML and CSS primitives wherever they exist.
Interactive decision checker
Do you even need JavaScript for this UI pattern?
Select a common interface requirement to see whether Modern Web Guidance prescribes zero-JS HTML/CSS or a lightweight modern DOM API.
Modal dialog with backdrop and Escape keyMinimal native HTML + 1-line trigger
Why legacy JS fails
Modern Web Guidance solution
Modern DOM & Components
When you do build custom elements
Form-Associated Custom Elements: Use formAssociated = true and ElementInternals so custom controls submit form values, react to reset/disable events and integrate with the native Constraint Validation API.
Declarative Shadow DOM: Define shadow roots directly in HTML with <template shadowrootmode="open"> (Baseline Widely available since August 2026), eliminating flashes of unstyled content without initial attachShadow() JS.
Observers over polling: Track element dimensions with ResizeObserver and DOM tree changes with MutationObserver instead of timer loops.
Accessibility in JavaScript
Keyboard focus, inert and screen readers
Native modals and inert: A <dialog> opened with showModal() already makes the rest of the page inert and returns focus when it closes, so don't add your own focus trap. Use the inert attribute for other cases, such as an off-screen drawer.
ARIA attribute reflection & ariaNotify(): Set accessibility properties directly on elements (such as btn.ariaExpanded = 'true') and trigger screen-reader announcements cleanly without hidden live-region DOM churn (ariaNotify() became Baseline Newly available in September 2026).
Adaptive input & gestures: Combine Pointer Events, touch-action, enterkeyhint and inputmode so mobile keyboards and swipe gestures feel native whilst respecting reduced-motion preferences.
Section 05 / Security, privacy & agentic web
Hardened security, passkeys and on-device capabilities
Modern Web Guidance places client-side security alongside performance, ensuring that scripts handling untrusted HTML, user credentials or network boundaries rely on browser-enforced primitives.
DOM XSS defence
Trusted Types & Sanitizer API
Assigning raw strings to innerHTML is a primary source of DOM-based cross-site scripting. Trusted Types (Baseline Newly available in February 2026) blocks unsafe string sinks at the browser level, whilst the Sanitizer API strips dangerous markup natively (Limited availability so far, so keep a fallback such as textContent).
Authentication
Passkeys, WebAuthn & FedCM
Guide users away from fragile password flows towards WebAuthn passkey registration, conditional creation after login, signal methods and Federated Credential Management (FedCM), plus WebOTP for SMS verification.
Network & crypto
Origins, SRI & WebCrypto
Parse and compare origins safely using URL and Origin rather than regexes. Enforce Subresource Integrity, Connection Allowlists and WebCrypto for client-side encryption and digital signatures.
Emerging platform
Built-in AI & WebMCP
For cutting-edge applications, Modern Web Guidance documents on-device AI APIs (LanguageDetector, LanguageModel, Summarizer, Translator) and WebMCP (document.modelContext and agentic JS tools).
Section 06 / Hands-on practice
Interactive legacy-scan audit simulator
When you run npx modern-web-guidance@latest legacy-scan ., the scanner flags outdated JavaScript patterns, performance traps and security hazards. Inspect a sample script below, click flagged lines to read the guidance and apply the modernised refactor.
Source file (click a flagged line after scanning)
Ready to scan
Inspecting legacy JavaScript
Click Run legacy-scan to check this snippet against Modern Web Guidance rules for Baseline compatibility, main-thread scheduling, security and DOM architecture.
Check your understanding
Three quick questions
Test your grasp of Modern Web Guidance rules for JavaScript. Feedback appears immediately beside each choice.
JavaScript & Web API feature index (filterable reference)Browse by domain