20 Little‑Known JavaScript APIs That 90% of Front‑End Developers Haven’t Used
This article introduces twenty under‑utilized native browser APIs—such as ResizeObserver, IntersectionObserver, Web Share, and WebCodecs—each explained with a single‑line code snippet, real‑world use cases, compatibility notes, and hidden tricks, showing how they can dramatically improve front‑end productivity and performance in 2025.
1. ResizeObserver: pixel‑level element size monitoring
Pain point: window.resize only tracks the viewport, leaving flex‑expanded chart containers invisible to callbacks.
One‑line code:
new ResizeObserver(entries => myChart.resize()).observe(document.querySelector('#chart'));Production scenarios: ECharts, AntV auto‑sizing, virtual scroll height recalculation.
Compatibility: Chromium 64+, Firefox 69+, Safari 13.1+ (polyfill ~3 KB).
2. IntersectionObserver: lazy‑load & exposure tracking with zero JS
Pain point: Hand‑written scroll listeners cause frame drops.
One‑line code:
const io = new IntersectionObserver(([{isIntersecting}]) => { isIntersecting && sendExposure(); }, {threshold: 0.5});
io.observe(document.querySelector('#ad'));Production scenarios: Image lazy‑loading, video auto‑play, exposure analytics.
Note: rootMargin supports values like "50px 0px" for pre‑loading.
3. Page Visibility: auto‑pause when the tab is hidden
Pain point: Background tabs keep polling and animating, wasting power.
One‑line code:
document.addEventListener('visibilitychange', () => { document.hidden ? video.pause() : video.play(); });Production scenarios: Live streams, games, polling APIs, WebSocket heartbeats.
Hidden gem: document.visibilityState can also be "prerender".
4. Web Share: system‑level sharing with a single call
Pain point: Building a custom share panel that works across Android, iOS, and desktop is painful.
One‑line code:
navigator.share({title: 'Whitepaper', text: '2025 Front‑End Trends', url: location.href});Production scenarios: One‑click sharing to WeChat, Telegram, email from an H5 page.
Note: Must be triggered by a user gesture and run over HTTPS.
5. Wake Lock: keep the screen on
Pain point: Live streams or presentations turn off the screen after 30 seconds, appearing as a freeze.
One‑line code:
const lock = await navigator.wakeLock.request('screen');Production scenarios: Live streaming, online meetings, in‑car HMI.
Hidden gem: The lock releases automatically on visibility change; re‑request if needed.
6. BroadcastChannel: intra‑origin "WeChat group" for tabs
Pain point: Logging in on tab A leaves tab B stuck on the login page after a 302 redirect.
One‑line code:
new BroadcastChannel('login').postMessage({token});Production scenarios: Sync login state, theme switching, cart merging.
Note: Works only within the same origin; cross‑origin use localStorage + storage events.
7. PerformanceObserver: non‑intrusive performance metric collection
Pain point: Manually calculating FCP, LCP, FID is tedious.
One‑line code:
new PerformanceObserver(list => { for (const entry of list.getEntries()) analytics.send(entry.name, entry.startTime); }).observe({type: 'paint'});Production scenarios: Gradual roll‑out performance regression checks, SLA dashboards.
Hidden gem: element entries expose the specific DOM node for LCP.
8. requestIdleCallback: run work during browser idle time
Pain point: Logging or analytics upload blocks the main thread and causes jank.
One‑line code:
requestIdleCallback(() => sendLogs(), {timeout: 2000});Production scenarios: Non‑critical log uploading, pre‑loading the next route.
Note: React 18’s startTransition is built on this API.
9. scheduler.postTask: native priority queue
Pain point: Background data sync steals CPU from user interactions.
One‑line code:
scheduler.postTask(refreshData, {priority: 'background'});Production scenarios: Low‑priority data sync, pre‑rendering.
Hidden gem: Supports signal and AbortController for cancellation.
10. AbortController: cancel fetch requests to avoid race conditions
Pain point: Switching tabs quickly lets stale responses overwrite fresh data.
One‑line code:
const ctrl = new AbortController();
fetch(url, {signal: ctrl.signal});
ctrl.abort(); // cancel anytimeProduction scenarios: Search autocomplete, route change cleanup.
Hidden gem: Can also cancel ReadableStream and scheduler.postTask.
11. ReadableStream: stream large files for download
Pain point: Loading a 1 GB installer into memory crashes the tab.
One‑line code:
const reader = response.body.getReader();
while (true) {
const {done, value} = await reader.read();
if (done) break;
await writeChunk(value);
}Production scenarios: Resumable downloads, progress bars.
Hidden gem: Combine with BYOB to reduce memory usage by ~30%.
12. WritableStream: stream large files for upload
Pain point: Sending a 500 MB CSV via xhr.send(blob) crashes the page.
One‑line code:
const writer = (await fetch(url, {method: 'POST', body: stream})).body.getWriter();Production scenarios: Real‑time log upload, SQLite backup.
Note: Server must support Transfer-Encoding: chunked.
13. Background Fetch: PWA resumable downloads
Pain point: Users download to 99% then lose connection (e.g., subway) and must restart.
One‑line code:
sw.registration.backgroundFetch.fetch('pkg', ['/1.zip', '/2.zip']);Production scenarios: App Shell assets, game resource packs.
Hidden gem: System notification bar shows progress and allows pause/resume.
14. File System Access: read/write local files from the browser
Pain point: Users want to save a .psd file but you can only offer a .zip download.
One‑line code:
const h = await window.showSaveFilePicker();
const w = await h.createWritable();
await w.write(blob);Production scenarios: Web IDEs, online Photoshop, Notion local backup.
Note: Requires explicit user interaction and HTTPS.
15. Clipboard: asynchronous clipboard API
Pain point: Legacy document.execCommand('copy') is deprecated.
One‑line code:
await navigator.clipboard.writeText('Hello, 2025!');Production scenarios: Code editors, online spreadsheets.
Hidden gem: clipboard.read() can read images for one‑click watermark removal tools.
16. URLSearchParams: ditch manual regex for query strings
Pain point: Manually concatenating "&" and "?" often leads to missing parameters.
One‑line code:
const p = new URLSearchParams({q: 'frontend', year: 2025});
console.log(p.toString()); // q=%E5%89%8D%E7%AB%AF&year=2025Production scenarios: Any GET request, pagination.
Hidden gem: URLSearchParams is iterable; you can use for‑of directly.
17. structuredClone: deep copy with circular references
Pain point: JSON.parse(JSON.stringify(obj)) drops functions, Dates, undefined, etc.
One‑line code: const copy = structuredClone(original); Production scenarios: Large Redux stores, canvas history.
Note: Supports Map/Set/Blob/File but not functions.
18. Intl.NumberFormat: locale‑aware number and currency formatting
Pain point: Backend returns 1234567.89 and you need to display "¥ 1,234,567.89".
One‑line code:
new Intl.NumberFormat('zh-CN', {style: 'currency', currency: 'CNY'}).format(1234567); // ¥1,234,567.89Production scenarios: E‑commerce pricing, stock tickers.
Hidden gem: The unit option can directly format units like "meter‑per‑second".
19. EyeDropper: browser‑level color picker
Pain point: Users need to pick a color from a page, but you have to compute pixels via Canvas.
One‑line code:
const {sRGBHex} = await new EyeDropper().open();Production scenarios: Online design tools, theme‑color extraction.
Note: Requires a user gesture and works on Chromium 95+.
20. WebCodecs: native hardware‑accelerated 4K video decoding
Pain point: H.265 10‑bit video stalls the browser like a PowerPoint slide.
One‑line code:
const decoder = new VideoDecoder({output: frame => canvas.draw(frame), error: e => console.error(e)});
decoder.configure({codec: 'hvc1.1.6.L120.90'});Production scenarios: Online video editing, cloud gaming, security camera feeds.
Hidden gem: Can run in a WebWorker, leaving the main thread at 0 % CPU.
2025 browsers have evolved far beyond their 5‑year‑old counterparts; mastering these twenty native APIs can dramatically boost your front‑end KPI.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
