0

What is the best way to avoid displaying an image when the screen width is less than 800px:s in next.js? The obvious problem with hiding it in CSS is that the image will still be downloaded by the browser.

Currently I can think of two solutions:

  1. Using srcset and showing a 1px image as demonstrated here: Suppressing downloads for hidden images using srcset + sizes
  2. Conditionally load the image client-side

Is there a better approach to this problem?

1 Answers1

-2

you might want to consider Server-side Rendering (SSR) or Static Site Generation (SSG). With these methods, you can decide on the server side whether to include the image in the HTML. This way, the image won't be downloaded at all if it's not needed.

example using the react-use library:

import { useWindowSize } from 'react-use'

export default function MyComponent() {
  const { width } = useWindowSize()

  return (
    <div>
      {width > 800 && <img src="my-image.jpg" alt="My Image" />}
    </div>
  )
}

This code only renders the image if the window width is greater than 800px. However, this won't handle window resizing after the page has loaded. To cover that, you could combine this with your client-side approach.

Emre Turan
  • 108
  • 3
  • 1
    Thank you! However, are you sure this is correct? How can the window width be known from the server? – Kasper Östberg Jul 11 '23 at 07:44
  • You're absolutely right, The server doesn't have access to the client's window width. That was my mistake. The solution I provided uses a client-side approach, where the window width is determined using JavaScript in the browser. – Emre Turan Jul 11 '23 at 12:37