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

推荐订阅源

T
Tenable Blog
博客园_首页
Vercel News
Vercel News
WordPress大学
WordPress大学
美团技术团队
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Y
Y Combinator Blog
博客园 - 【当耐特】
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
腾讯CDC
M
MIT News - Artificial intelligence
爱范儿
爱范儿
Recent Announcements
Recent Announcements
雷峰网
雷峰网
Last Week in AI
Last Week in AI
宝玉的分享
宝玉的分享
The Register - Security
The Register - Security
Jina AI
Jina AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
P
Privacy & Cybersecurity Law Blog
Recorded Future
Recorded Future
Help Net Security
Help Net Security
N
News and Events Feed by Topic
博客园 - Franky
P
Proofpoint News Feed
L
LINUX DO - 热门话题
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
D
Docker
Google DeepMind News
Google DeepMind News
有赞技术团队
有赞技术团队
IT之家
IT之家
Security Latest
Security Latest
L
LangChain Blog
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
J
Java Code Geeks

CSS Wizardry

Front-End’s Missing Metric: The TBT Window Meet Your Users Where They Are with Obs.js Better Browser Caching with No-Vary-Search font-family Doesn’t Fall Back the Way You Think What Is CSS Containment and How Can I Use It? When All You Can Do Is All or Nothing, Do Nothing Low- and Mid-Tier Mobile for the Real World (2025) The Fastest Site in the Tour de France Making Sense of the Performance Extensibility API Why Do We Have a Cache-Control Request Header? HTML Is Not a Programming Language… Build for the Web, Build on the Web, Build with the Web Licensing Code on CSS Wizardry A Layered Approach to Speculation Rules Designing (and Evolving) a New Web Performance Score Core Web Vitals Colours The Ultimate Contract Templates for Tech Consultants: Protect Your Business and Get Paid Optimising for High Latency Environments Cache Grab: How Much Are You Leaving on the Table? blocking=render: Why would you do that?! Correctly Configure (Pre) Connections The Three Cs: 🤝 Concatenate, 🗜️ Compress, 🗳️ Cache What Is the Maximum max-age? How to Clear Cache and Cookies on a Customer’s Device The Ultimate Low-Quality Image Placeholder Technique Core Web Vitals for Search Engine Optimisation: What Do We Need to Know? The HTTP/1-liness of HTTP/2 In Defence of DOM­Content­Loaded Site-Speed Topography Remapped Why Not document.write()? Speeding Up Async Snippets Critical CSS? Not So Fast! Measure What You Impact, Not What You Influence Optimising Largest Contentful Paint Measuring Web Performance in Mobile Safari Site-Speed Topography Speed Up Google Fonts Real-World Effectiveness of Brotli Performance Budgets, Pragmatically Lazy Pre-Browsing with Prefetch Making Cloud.typography Fast(er) Time to First Byte: What It Is and How to Improve It Self-Host Your Static Assets Tips for Technical Interviews Cache-Control for Civilians Bandwidth or Latency: When to Optimise for Which ITCSS × Skillshare What If? CSS and Network Performance The Three Types of Performance Testing Getting to Know a Legacy Codebase Image Inconsistencies: How and When Browsers Download Images Identifying, Auditing, and Discussing Third Parties My Digital Music Setup Measuring the Hard-to-Measure Finding Dead CSS The Fallacies of Distributed Computing (Applied to Front-End Performance) Ten Years Old Relative Requirements Airplanes and Ashtrays Performance and Resilience: Stress-Testing Third Parties Refactoring Tunnels Little Things I Like to Do with Git Writing Tidy Code Configuring Git and Vim Base64 Encoding & Performance, Part 2: Gathering Data Base64 Encoding & Performance, Part 1: What’s Up with Base64? Code Smells in CSS Revisited Typography for Developers Moving CSS Wizardry onto HTTPS and HTTP/2 Ack for CSS Developers A New Year, a New Focus Preparing Vim for Apple’s Touch Bar Choosing the Correct Average CSS Shorthand Syntax Considered an Anti-Pattern CSS Wizardry Newsletter Nesting Your BEM? Improving Perceived Performance with Multiple Background Images Continue Normalising Your CSS Pure CSS Content Filter Pragmatic, Practical, and Progressive Theming with Custom Properties Refactoring CSS: The Three I’s Speaker’s Checklist: Before and After Your Talk Improving Your CSS with Parker The Importance of !important: Forcing Immutability in CSS Mixins Better for Performance Managing Typography on Large Apps White October Events Workshop Partnership BEMIT: Taking the BEM Naming Convention a Step Further Travelling Like You Want to, When You Have To Contextual Styling: UI Components, Nesting, and Implementation Detail Subtleties with Self-Chained Classes Cyclomatic Complexity: Logic in CSS Immutable CSS Can CSS Be Too Modular? More Transparent UI Code with Namespaces When to use @extend; when to use a mixin The Specificity Graph CSS Wizardry Ltd.: Year 1 in review CSS Guidelines 2.0.0
Obs.js: Context-Aware Web Performance for Everyone
Harry Roberts · 2025-08-27 · via CSS Wizardry

Written by on CSS Wizardry.

Table of Contents

Independent writing is brought to you via my wonderful Supporters.

  1. Why It Must Run Early
  2. What It Gives You
  3. CSS API
  4. JS API
  5. Statuses and Stances
  6. SPAs and Long-Lived Pages
  7. Analytics
  8. Unsupported Browsers
  9. A Few Quick Wins

For the last several weeks, I’ve been working on a new JavaScript library called Obs.js. If you want the broader case for why I think this kind of thing matters, I’ve written that up separately in Meet Your Users Where They Are with Obs.js. This post is the more technical counterpart: what Obs.js gives you, how it works, and where I think it becomes useful.

In a nutshell, Obs.js is a tiny inline script that reads a handful of browser signals available to us and exposes them as:

  • classes on the <html> element, and
  • properties on a window.obs object.

That means we can adapt our UI to the context in which it is being consumed: avoid web fonts on weak connections, serve lower resolution media when the browser signals caution, tone down motion when battery is low, or simply beacon that context off to analytics for later analysis.

Why It Must Run Early

Obs.js is very simple to install, but intentionally very strict: it needs to be inlined in the <head> before any HTML, CSS, or JavaScript that might depend on it:

<script>
  // Obs.js here
</script>

It will auto-terminate if you attempt to include it via an external file, or run it asynchronously via type=module.

That’s not me being difficult for the sake of it; it is the whole point. If the script exists to inform early decisions about the page, it needs to be there early enough to influence those decisions. If it ran asynchronously, or too late, we’d likely end up doubling work and, ironically, making everything slower.

Thankfully, Obs.js is under 1.5KB Gzipped and takes less than 5ms to run on a low-end device, so the inline cost is very small.

What It Gives You

At a glance, Obs.js gives you access to a number of CSS classes that are automatically added to the <html> element, and a window.obs object that exposes the same information via JavaScript.

You may see classes along the lines of:

<html class="has-latency-high
             has-bandwidth-low
             has-connection-capability-weak
             has-conservation-preference-conserve
             has-delivery-mode-lite">

And in JS:

window.obs.connectionCapability   // 'strong' | 'moderate' | 'weak'
window.obs.deliveryMode           // 'rich' | 'cautious' | 'lite'
window.obs.dataSaver              // true | false
window.obs.batteryLow             // true | false | null
window.obs.deviceCapability       // 'strong' | 'moderate' | 'weak'

The full matrix is in the README, but the key idea is that Obs.js gives you a lightweight way to reason about transport, power, and hardware constraints.

CSS API

The CSS API is probably the quickest way to get started with Obs.js. On my own homepage, I use Obs.js to swap the masthead background depending on the browser’s inferred delivery mode:

.page-head--masthead {
  background-image:
    url(/img/css/masthead-small.jpg), /* Full-res hero image. */
    url(/img/css/masthead-small-lqip.jpg),
    var(--base64);
}

.has-delivery-mode-lite .page-head--masthead {
  background-image:
    url(/img/css/masthead-small-lqip.jpg), /* LQIP only on poorer connections. */
    var(--base64);
}

In other words, visitors in lite mode get the much cheaper low-quality placeholder stack rather than the richer image stack. I repeat the same pattern at larger breakpoints with the medium and large masthead assets, but the principle is the same: meet the browser where it says the user currently is.

Also, the CSS for my drawer menu:

.has-battery-low .site-nav__list,
.has-battery-critical .site-nav__list {
  transition: none;
  will-change: auto;
}

If someone’s battery is low or critical, I simply drop the slide-in transition. Again, incredibly boring, but a perfectly reasonable little consideration.

JS API

If you need a little more control, the JS API is there too. For example, let’s only preload a web font if the connection capability is not weak:

if (window.obs?.connectionCapability !== 'weak') {
  const preload = document.createElement('link');
  preload.rel = 'preload';
  preload.as = 'font';
  preload.type = 'font/woff2';
  preload.crossOrigin = 'anonymous';
  preload.href = '/fonts/my-font.woff2';
  document.head.appendChild(preload);
}

You could just as easily use this to decide whether to instantiate a video, eagerly load a carousel, or avoid a non-essential enhancement on a weaker device.

The point is not that Obs.js makes the decision for you, but that it gives you better information with which to make it yourself.

Statuses and Stances

Obs.js is based on the two core ideas of Statuses and Stances.

A Status is a factual piece of information exposed by the browser, for example:

  • the user has Data Saver enabled,
  • the observed latency is high,
  • the battery is low, or,
  • the device appears memory-constrained.

A Stance is an opinion Obs.js takes in response:

  • the connection looks weak,
  • the user may prefer to conserve resources,
  • the safest delivery mode is lite, or,
  • rich media is probably not a great idea right now.

This distinction is useful because it keeps raw signals separate from the decisions you might make with them. If you want the bare-metal facts, you can use them; if you want a quicker, more ergonomic answer, you can lean on deliveryMode, canShowRichMedia, or shouldAvoidRichMedia.

SPAs and Long-Lived Pages

For most ordinary websites, Obs.js can be dropped into the <head> with no further configuration. It runs once on page load, which is usually enough for most use cases.

However, if you have a long-lived page or a single-page application, Obs.js may eventually become stale. To combat that, it exposes a config option:

<script>window.obs = { config: { observeChanges: true } };</script>

<script>
  // Obs.js here
</script>

With observeChanges: true, Obs.js can listen for changes in the relevant signals and update its classes and window.obs values accordingly, without the page needing a reload.

Analytics

Obs.js is not only useful for adaptation, but is also a handy segmentation layer for analytics. If your analytics tooling supports custom dimensions, you can beacon some of the Obs.js data off alongside your normal performance telemetry.

I use SpeedCurve, so for me that might be as simple as:

LUX.addData('Latency', obs.rttBucket);
LUX.addData('DeliveryMode', obs.deliveryMode);

At that point, your metrics stop being one opaque average and start becoming more explainable. You can ask how weaker devices fare compared to stronger ones, or how much high-latency visitors differ from the rest. For example, one client who uses Obs.js discovered that their conversion rates are higher when customers are running low on battery. I’ll let you do what you want with that information…

Unsupported Browsers

Most of the underlying APIs are only available in Chromium browsers. This means you need to decide how to handle notable absentees like iOS yourself—Obs.js does not make that decision for you.

Broadly, your choices are:

  1. default to the richer experience and let Obs.js selectively dial things down, or;
  2. default to the lighter experience and let Obs.js selectively dial things up.

Either is valid, but the important thing is that you choose carefully and deliberately.

A Few Quick Wins

If you are wondering where to start, keep it simple. Obs.js is immediately useful for things like:

  • swapping a homepage masthead down to its LQIP-only version for has-delivery-mode-lite,
  • removing transitions when the battery is low or critical,
  • avoiding web fonts on weak connections,
  • skipping autoplay or rich media unless the browser clearly signals that the visitor can afford it, or,
  • segmenting analytics by latency, delivery mode, or device capability.

Those are all pretty small interventions, but together they can make the front end feel a lot more sympathetic to the user’s circumstances.

Obs.js is running on its demo page right now, and the repo—including obs.js itself—is there if you want to inspect the code. It is one of the most quietly useful little things I’ve built in a long while.

Using Obs.js already? Open a Pull Request to submit your site to the showcase.


Frequently Asked Questions

What is Obs.js?

Obs.js is a tiny inline script that reads available browser signals such as network conditions, battery, memory, and CPU, then exposes that context to CSS and JavaScript.

How do I install Obs.js?

Obs.js must be pasted as an inline classic script in the head of the document, before any HTML, CSS, or JavaScript that depends on it.

Why must Obs.js be inline in the head?

Because it is designed to inform early delivery decisions. Loading it externally or asynchronously would make it later, less reliable, and potentially self-defeating.

Does Obs.js work in Safari?

Only partially. Most of the underlying APIs are Chromium-heavy, so you need to decide what fallback experience Safari and other unsupported browsers should receive.

Can Obs.js update on long-lived pages?

Yes. If you set `window.obs.config.observeChanges` to `true`, it can listen for changes to the relevant browser signals and update itself on longer-lived pages or SPAs.