Web Video && Network Speed Detection in JavaScript vs. UX
Tags: javascript, webdev, sustainability, ux
Published: 2022-03-14 09:58:33

Wouldn't it be nice if we could write something like `<has-network min="2g"><video>` or `<video><source network="(min-speed: 2g)">` to skip video loading if there's no sufficient bandwidth? But there is nothing like this in HTML. Why is it not that simple and what to can we do instead?

## Web Video based on effective Network Speed

Let me start with some user stories because I'm a professional (and a sustainable web developer). The actual optimization of web video is only one aspect of this article, and if you don't have time to read, you can [skip to the solution](#the-solution-code).

The first user story (not *that* professional) is my own story:

{% comment https://dev.to/ingosteinke/comment/1k3oc %}

## 1. Use Case: being all but Offline

I keep getting all those (un)helpful messages telling me to check my internet connection or assuming I am offline. Did we become so accustomed to being always connected to the world's most important online services? Let's not forget that the internet was supposed to be a [resilient decentralized network](https://www.akamai.com/blog/performance/internet-resilience-part2-what-it-takes-to-just-work) of peers where data eventually finds a way from one device to another?

[![Statistics: 50 percent of rural America without internet access in 2019. Disconnected: 2.9 billion people still offline, source: ITU, quoted from statista.com](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z335v13l8bggbt3l1aty.png)](https://www.statista.com/chart/25549/households-with-internet-access-by-area-and-region/) [Source: ITU / Statista.com](https://www.statista.com/chart/25549/households-with-internet-access-by-area-and-region/)

## 2. Use Case: having to Pay for Bandwidth

Shocking truth: some people have to pay a lot of money for every byte that's transmitted over the network. Yes, the shiny high resolution hero images, the auto-play 4K home page videos, and the all-purpose JavaScript framework constantly fetching annoying adverts and irrelevant updates from servers don't make a website look and feel as good as it did in our hipster agency office when we try to open it on a mobile screen in a crowded bus in the middle of nowhere.

[![Statistics: The cost of 1 GB of mobile data in every country, source: Digital Information World](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v76f11vpgub5req7e0sy.png)](https://www.digitalinformationworld.com/2020/07/the-average-cost-of-1gb-mobile-data-around-the-world.html) [Source: Digital Information World](https://www.digitalinformationworld.com/2020/07/the-average-cost-of-1gb-mobile-data-around-the-world.html)

## 3. Use Case: Saving our Planet

Testing a website with services like [WebsiteCarbon.com]((https://websitecarbon.com/)), you might have seen another shocking truth: The internet is a huge waste of energy! The games we play, the videos and music we stream, and the websites we build for our customers all consume energy that has to be produced somehow.

[![Website Carbon analytics result: "Uh oh! This web page is dirtier than 59% of web pages tested. Oh my, 1.21g of CO2 is produced every time someone visits this web page."](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s65zfsju1t5nnlej96u5.png)](https://websitecarbon.com/)

Like turning sunshine into electric energy. Or the the flow of wind and water. That's called renewable energies, and that's still rarely used. Instead, energy providers buy fossil fuels like oil and gas from dictators and their industries to heat our homes, fuel our cars, and provide us with entertaining content on the internet.

![Statistics: Coal, oil, and natural gas remain the primary global energy sources even as renewables have begun rapidly increasing, Source: Wikipedia. Greenpeace points out that binge watching Netflix is bad for the environment, Source: CompareBroadband.com](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c2z0g81yw7a5kfxj9u4l.png) Sources: [Wikipedia](https://en.wikipedia.org/wiki/Energy_transition), [CompareBroadband.com](https://www.comparebroadband.com.au/broadband-articles/latest-news-id3/greenpeace-points-out-that-binge-watching-netflix-is-bad-for-the-environment-id1138/)

## 4. Use Case: Ethical Marketing

Even if you don't care about the environment or people getting killed because they happen to live on a soil that promises to provide profitable resources, you might care about customer satisfaction and return on investment.

If we want to keep using our cars and watch cool music videos  with a clear conscience, we should at least stop adding to the useless waste of energy with the code that we write today. Otherwise we'll be part of those idiots that caused our customers to drown in the next social media shitstorm.

![Screenshot of a critical photo collage in a YouTube player showing a fire above a blue barrel with Gazprom branding, Trump with Saudi prince, and a photo montage of Putin and Hitler with the motto: destroy Putler (Putler kaput! Путлер капут!)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hfz8i0rxvn6lkpxsjj1m.png)

## 5. Use Case: making our Customers Happy
When our website finally loaded all the images and videos your customers never wanted to watch in the first place, they might engage by installing an ad-blocker and limiting data transmitted over mobile networks.

[![Statistics: US ad blocking users, by select generation, 2014 - 2018, reasons why people use ad blocking, the spread of ad blocking in each region, source: emarketer.com](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/102oszuql8k2q2jyvduw.png)](https://www.emarketer.com/) [Source: emarketer.com](https://www.emarketer.com/)

## 6. Use Case: proving Our Tech Skills

Why not try to detect our customer's preferences and possibilities as good as we can? That's what an elite rock star code ninja is supposed to do, because we can!

![Screenshot of my network connection API implementation in JavaScript, the StackOverflow logo, and a notification about new positive reputation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtqdzdsgbpoe2stsr0mx.png)

So at least, let's do something good for the wrong reason and earn some reputation on DEV and StackOverflow ;-)

## Network Detection to the Rescue

We can check for various user settings in our websites these days. Does our user [prefer reduced motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion), do they [like dark mode](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme?ref=hackernoon.com)? Do they use [high contrast settings](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-contrast)? Are they viewing our site [on a small screen or printed on paper](https://developer.mozilla.org/en-US/docs/Web/CSS/@media)?

![Screenshot of Firefox developer tools Network tab and throttling options](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qywtqm6w6xuq4cwnmpgx.png)

To test our checks, we can also [emulate features and media conditions in our browsers' developer tools](https://developer.mozilla.org/en-US/docs/Tools/Responsive_Design_Mode): resize our screens, pretend we're using a touch device or a printer, disable `webp` support, and we can also throttle our download speed.
<a name="the-solution-code"></a>
## The Network Information API

Unlike some feature detection available in HTML and CSS, the [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) is currently only available in JavaScript.

## Show me the Code

```javascript
const hasFastConnection = function hasFastConnection() {
  /** @var {NetworkInformation} connection */
  const connection = navigator.connection
    || navigator.mozConnection
    || navigator.webkitConnection;
  return (!connection || (
    !connection.saveData
    && connection.type !== 'none'
    && connection.effectiveType !== 'slow-2g'
    && connection.effectiveType !== '2g'
    && connection.effectiveType !== 'slow-3g'
  ));
};
```

So we're all set? No, we've actually built a very naive solution that might turn out to be a [Verschlimmbesserung](https://www.dictionary.com/e/translations/verschlimmbesserung/).

## What's Wrong with the Code?

Apart from the hackish syntax forcing us to compare magic strings with no chance for numeric comparison, finer granularity, and future enhancement, and no idea if `4g` would be twice as fast as `2g` and if we should assume a `1g` or `5g` value without looking up the API documentation...

... even if we manage to make a valid measurement:

### What are our assumptions?

#### One Moment in Time?

What is an "effective network speed" when I'm in a train that has high speed internet next to a city center but I'm practically offline inside a long tunnel? What if the server was terribly slow at the time of measurement although the connection is perfectly quick otherwise?

#### They can't wait to watch this Video!

Even if we do measure the right thing at the right time: just because our users *can*, that doesn't necessarily imply that they *want to*. Just because there is a sufficient network connection still doesn't mean our users are interested in downloading and watching a certain video. Even if the marketing department thinks so.

## 7. Use Case: too much Web Video!

As @dougsillars said at [one of our Web Performance meetups](https://www.meetup.com/cologne-germany-high-performance-website-optimization-group/events/267964943/): "the best web video (at least in the eyes of web speed optimization) is the one that does not load." The worst case is even more common: videos that load, never to be played.

{% youtube https://www.youtube.com/watch?v=7Q3hT2h5K5I %}

Like carousel sliders and animations, customers or rather their marketing teams love video. Kids love video. Teenagers love video. Take Tiktok etc. or YouTube for the older generation, platforms full of mostly irrelevant content. But at least those platforms are professionals that know how to serve videos without wasting bandwidth. Because if they didn't, they would waste bandwidth and server costs they have to pay for themselves.

{% post https://dev.to/api_video/responsive-video-delivery-3gfd %}

Self hosting is nice, using a professional service is better (and if you're in Europe, make sure if you're even allowed to use international providers like YouTube without violating [GDPR laws](https://gdpr.eu/).

Maybe your website can do without a video, but you can't?

## Conclusion

Use cloud services that are experts for optimized delivery, and choose a service that respects your country's privacy laws.

Avoid unnecessary web video!
Don't ever auto-play videos!

Become an ethical developer and stop being part of the problem!