search
HomeWeb Front-endCSS TutorialOptimize Images According to Network and Device Constraints in React

Optimize Images According to Network and Device Constraints in React

Network connectivity technology has undergone earth-shaking changes since the birth of the Internet. We have long bid farewell to the era of dial-up Internet access, and now we can watch high-definition videos on mobile networks with smartphones. But not all mobile network connections are the same - older generation networks (3G, 2G, etc.) still dominate, and nearly half of the world's connections belong to this type of network in 2020.

Unfortunately, the process of eliminating old networks is very slow, and many people around the world still face the problem of slow page loading, which is reminiscent of the early days of the popularity of home Internet.

Modern websites have become resource-intensive, with a lot of pictures and animations. For visitors using low-performance devices and unstable network connections, a normal web page may take one minute to fully load. This is mainly because developers tend to make binary decisions when dealing with user hardware and network conditions: devices either belong to the desktop category or smartphone category; connection status is either online or offline. In fact, the user's environment is often more detailed and complex.

Can we do better?

How to bridge the gap between those users who use low-end devices and unstable network connections? First, we need to quickly evaluate their specific situation by looking at the following two properties:

  • navigator.deviceMemory
  • navigator.connection

Based on this, we can decide to adjust the image quality to provide. However, there is a problem with Jamstack websites and applications rendering on the server side - navigator objects and any other browser APIs are not available during the rendering phase. A common way to solve this problem is to add a lot of responsive image markers, but this brings a significant pain point - inefficient scaling. Image CDNs like ImageEngine can help avoid this problem and other pitfalls associated with responsive images, as it handles all the heavy lifting by making instantly automatic intelligent adjustments to the requested resources.

In terms of adapting to user network limitations, the connection type can be detected and the image CDN is instructed to change the compression rate according to the connection quality. Here's how to implement this in React:

 import React, { useState, useEffect } from 'react'

const useConnectionType = (defaultConnectionType) => {

  const isSupported = navigator?.connection?.effectiveType
    ? true
    : false

  const [connectionType, setNetworkStatus] = useState(
    isSupported
      ? navigator.connection.effectiveType
      : defaultConnectionType
  )

  useEffect(() => {
    if (isSupported) {
      const { connection } = navigator
      const updateConnectionType = () => {
        setNetworkStatus(connection.effectiveType)
      }

      connection.addEventListener('change', updateConnectionType)

      return () => {
        connection.removeEventListener('change', updateConnectionType)
      }
    }
  }, [])

  return [connectionType, setNetworkStatus ]
}

const imageCDNHost = 'images.foo.com'

function ConnectionAwareComponent () {

  const [connectionType] = useConnectionType()

  let compressionLevel = 0

  switch (connectionType) {
    case 'slow-2g':
      compressionLevel = 65
      break
    case '2g':
      compressionLevel = 50
      break
    case '3g':
      compressionLevel = 30
      break
    case '4g':
      compressionLevel = 0
      break
  }

  Return (
    <div>
      {/* Use dedicated instructions to apply variable compression*/}
      <img  src="%7B%60%24%7BimageCDNHost%7D/?imgeng?=cmpr_%24%7BcompressionLevel%7D%60%7D" alt="Optimize Images According to Network and Device Constraints in React" >
    </div>
  )
}

We can go a step further, provide blurred images for users with very slow networks and offer the option of downloading higher resolution versions on demand. Or design a performance scoring system and adjust the sent content based on the system.

On the other hand, users using a "high-speed" 4G connection does not necessarily mean they don't care about saving data, as they may visit the website in a roaming state. Enabling client prompts on the website will enable the site owner to detect the presence of a data saving flag and take the necessary steps to adapt to the user's preferences.

Reasons for faster images

Medium CPU, proper amount of memory, and low-level connections are not fictional limitations. They pose a real user experience challenge that could affect hundreds of millions of users around the world. Some companies are starting to incorporate their products into an inclusive experience: streaming services like Netflix and Spotify adjust streaming quality based on your network condition, while many others are behind the scenes to automatically optimize image for users.

In underdeveloped areas where the Internet is not yet popular, it may not be the target market. Meanwhile, if users from rural areas of developed countries are provided with a full version of the website, they may experience an unpleasant experience. We can adjust the content sent/displayed to the user more considerately with some small adjustments.

Using an image CDN like ImageEngine can simplify the image optimization process and automatically respond to client prompts for network restrictions. The result is a better experience for network-constrained visitors and an elegant workflow for developers.

The above is the detailed content of Optimize Images According to Network and Device Constraints in React. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Slideout FooterThe Slideout FooterApr 09, 2025 am 11:50 AM

A fascinating new site called The Markup just launched. Tagline: Big Tech Is Watching You. We’re Watching Big Tech. Great work from Upstatement. The

Pages for LikesPages for LikesApr 09, 2025 am 11:47 AM

I posted about parsing an RSS feed in JavaScript the other day. I also posted about my RSS setup talking about how Feedbin is at the heart of it.

Recreating the CodePen Gutenberg Embed Block for Sanity.ioRecreating the CodePen Gutenberg Embed Block for Sanity.ioApr 09, 2025 am 11:43 AM

Learn how to create a custom CodePen block with a preview for Sanity Studio, inspired by Chris Coyier’s implementation for Wordpress’ Gutenberg editor.

How to Make a Line Chart With CSSHow to Make a Line Chart With CSSApr 09, 2025 am 11:36 AM

Line,  bar, and pie charts are the bread and butter of dashboards and are the basic components of any data visualization toolkit. Sure, you can use SVG

Programming Sass to Create Accessible Color CombinationsProgramming Sass to Create Accessible Color CombinationsApr 09, 2025 am 11:30 AM

We are always looking to make the web more accessible. Color contrast is just math, so Sass can help cover edge cases that designers might have missed.

How We Created a Static Site That Generates Tartan Patterns in SVGHow We Created a Static Site That Generates Tartan Patterns in SVGApr 09, 2025 am 11:29 AM

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

A Follow-Up to PHP TemplatingA Follow-Up to PHP TemplatingApr 09, 2025 am 11:14 AM

Not long ago, I posted about PHP templating in just PHP (which is basically HEREDOC syntax). I'm literally using that technique for some super basic

Creating a Modal Image Gallery With Bootstrap ComponentsCreating a Modal Image Gallery With Bootstrap ComponentsApr 09, 2025 am 11:10 AM

Have you ever clicked on an image on a webpage that opens up a larger version of the image with navigation to view other photos?

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.