阿里云主机折上折
  • 微信号
Current Site:Index > Front-end trivia: those forgotten APIs like "tea stains"

Front-end trivia: those forgotten APIs like "tea stains"

Author:Chuan Chen 阅读数:41152人阅读 分类: 前端综合

Those APIs Forgotten Like "Tea Stains"

Front-end development is like brewing tea—over time, some "tea stains" inevitably settle: APIs that were once popular but gradually forgotten. They may no longer be trendy, but in certain scenarios, they can still brew surprisingly delightful "tea aromas."

document.designMode

// Enable editable mode for the entire document
document.designMode = 'on';
// Now you can modify page content like editing a Word document

This API, born in the IE era, can make the entire document editable. While modern rich text editors use contenteditable for localized editing, when quickly prototyping, typing this line in the console allows real-time adjustments to page text, far more efficient than repeatedly modifying code and recompiling.

navigator.vibrate()

// Vibrate the phone for 200ms
navigator.vibrate(200);
// Complex vibration pattern: vibrate 300ms, pause 100ms, vibrate 500ms
navigator.vibrate([300, 100, 500]);

This mobile-specific vibration API is often used for game feedback or important notifications. Interestingly, calling it in Chrome's desktop version won't throw an error—it just fails silently. This design allows code to run cross-platform without additional compatibility handling.

Hidden console Methods

console.table([
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 }
]);

// Output styled logs
console.log('%cRainbow text', 'background: linear-gradient(to right, red, orange); color: white; padding: 5px;');

Beyond the commonly used log/warn/error, the console object hides many gems. console.table displays array objects in tabular form, console.dirxml shows DOM node trees, and you can even create colorful logs using CSS syntax. For debugging complex data structures, these methods are far more intuitive than plain log.

requestIdleCallback

function processData(data) {
  // Big data processing logic
}

requestIdleCallback(deadline => {
  while (deadline.timeRemaining() > 0) {
    processData(nextChunk);
  }
});

This API allows the browser to execute tasks during idle periods, avoiding blocking critical rendering. Unlike setTimeout, it automatically schedules tasks during frame rendering gaps, making it ideal for non-urgent background tasks. React's Fiber architecture uses this for task slicing.

Forgotten CSS Counters

/* Auto-number chapter headings */
body {
  counter-reset: section;
}
h2::before {
  counter-increment: section;
  content: "Chapter " counter(section) " ";
}

Pure CSS counters can auto-generate table of contents numbering and ordered list styles. Even more magical, they support nested counting:

ol { counter-reset: item }
li { display: block }
li:before {
  counter-increment: item;
  content: counters(item, ".") " ";
}

The Magic of the details Element

<details>
  <summary>Click to reveal the answer</summary>
  <p>42 - The Answer to the Ultimate Question of Life, the Universe, and Everything</p>
</details>

This native HTML element implements an accordion effect without JavaScript. Custom arrow styles can be added via CSS:

details summary::-webkit-details-marker {
  display: none;
}
details summary:after {
  content: "+";
}
details[open] summary:after {
  content: "-";
}

The Internationalized Intl API

new Intl.RelativeTimeFormat('zh', { 
  numeric: 'auto' 
}).format(-1, 'day'); // Output: "昨天"

new Intl.ListFormat('zh').format(['苹果', '香蕉']); // Output: "苹果和香蕉"

When handling date, number, or list formatting, the Intl API series automatically adapts to localization rules. Compared to writing custom formatters, it supports 150+ language locales and even considers pluralization rules:

// Russian has special plural rules
new Intl.PluralRules('ru').select(2); // Returns "few"

Vanished DOM Traversal APIs

// Get all text nodes of an element
function getTextNodes(el) {
  const walker = document.createTreeWalker(
    el, 
    NodeFilter.SHOW_TEXT, 
    null, 
    false
  );
  const nodes = [];
  while (walker.nextNode()) nodes.push(walker.currentNode);
  return nodes;
}

TreeWalker and NodeIterator, these ancient DOM traversal APIs, have been largely replaced by querySelector in modern front-end development. But when fine-grained node traversal control is needed (e.g., processing rich text editor content), they remain irreplaceable.

Geofencing API

const fence = new CircularGeofence({
  latitude: 39.9042,
  longitude: 116.4074,
  radius: 1000 // 1km range
});

fence.onenter = () => console.log('Entered Tiananmen Square area');
fence.onexit = () => console.log('Left Tiananmen Square area');

While the Geolocation API is well-known, its enhanced version, GeographicFencing, is rarely mentioned. This API triggers callbacks when users enter/leave specific geographic areas, making it ideal for location-sensitive apps (e.g., auto-switching city services).

Underrated Web Animations API

const animation = element.animate([
  { transform: 'rotate(0deg)' },
  { transform: 'rotate(360deg)' }
], {
  duration: 1000,
  iterations: Infinity
});

// Precise animation control
document.querySelector('button').onclick = () => {
  animation.pause();
  animation.currentTime = 500; // Jump to mid-frame
};

Compared to CSS animations, this API offers finer control: dynamically modifying keyframes, querying playback states, and seamlessly chaining animation sequences. Most impressively, the returned Animation object natively supports Promises:

await element.animate([...], 1000).finished;
console.log('Animation complete!');

The Magical Web Share API

// Invoke the system's native share dialog
navigator.share({
  title: 'Front-end Trivia',
  url: 'https://example.com'
}).catch(e => {
  // Triggered when the user cancels sharing
});

On mobile devices, this API can summon the system-level share panel, supporting sharing to any installed app. Even better, it follows the "progressive enhancement" principle—calling it in unsupported browsers won't throw errors, allowing graceful fallbacks:

if (navigator.share) {
  // Modern sharing
} else {
  // Traditional share buttons
}

Time Traveler: console.timeTravel()

console.timeTravel(1000); // Rewind 1 second
console.log(new Date()); // Shows the time 1 second ago

This Firefox DevTools-private API modifies the page's perceived system time, making it useful for testing time-sensitive logic. Though non-standard, it inspires thought: when debugging time-sensitive apps, controlling "time flow" might be more efficient than repeatedly adjusting the system clock.

Font Detection API

document.fonts.ready.then(() => {
  console.log('All fonts loaded');
});

// Check if a specific font is available
document.fonts.check('12px "Source Han Sans"');

The FontFaceSet interface provides font loading state queries, especially useful for scenarios requiring precise text rendering control (e.g., avoiding font flickering). Paired with the CSS Font Loading API, more nuanced font loading strategies can be implemented:

const font = new FontFace('MyFont', 'url(myfont.woff2)');
await font.load();
document.fonts.add(font);

Vanished CSS Expressions

/* IE5-era black magic (deprecated) */
width: expression(document.body.clientWidth > 600 ? "600px" : "auto");

Though disabled in modern browsers, this design of writing JavaScript directly in CSS somewhat foreshadowed later CSS-in-JS techniques. Its deprecation also reminds us: powerful features come at the cost of performance.

Rich Text in Clipboard

// Read rich text from clipboard
navigator.clipboard.read().then(data => {
  const html = data.find(item => item.type === 'text/html');
  console.log(html);
});

// Write styled rich text
const item = new ClipboardItem({
  'text/html': new Blob(['<b>Hello</b>'], { type: 'text/html' })
});
navigator.clipboard.write([item]);

The modern Clipboard API handles not just plain text but also rich text content. This is practical for editor scenarios requiring preserved formatting, such as copying styled text from Word documents to web editors.

Overlooked Performance API

// Measure function execution time
performance.mark('start');
expensiveOperation();
performance.mark('end');
performance.measure('Duration', 'start', 'end');

// Get all resource loading times
performance.getEntriesByType('resource').forEach(resource => {
  console.log(`${resource.name} load time: ${resource.duration}ms`);
});

This API offers nanosecond-precision timing, more accurate than manually using Date.now(). Particularly, performance.now() is unaffected by system time adjustments, making it ideal for precise timing scenarios like animation frame rate statistics.

Browser "Spy" APIs

// Detect if the user prefers reduced motion
const prefersReducedMotion = window.matchMedia(
  '(prefers-reduced-motion: reduce)'
).matches;

// Listen for dark mode changes
window.matchMedia('(prefers-color-scheme: dark)')
  .addListener(e => {
    console.log(e.matches ? 'Dark mode' : 'Light mode');
  });

The JavaScript version of CSS media queries not only reads device features but also listens for changes in real time. From screen orientation and memory size to touch device detection, this information helps developers create more adaptive interfaces.

Element Size Observer

const observer = new ResizeObserver(entries => {
  entries.forEach(entry => {
    console.log(`Element width changed to: ${entry.contentRect.width}px`);
  });
});
observer.observe(document.getElementById('resizable'));

Instead of frequently polling offsetWidth, this API actively notifies when element dimensions change. Combined with MutationObserver and IntersectionObserver, modern browsers provide a complete DOM change monitoring system.

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.