Optimal Approach for Displaying Different Content on Mobile and Desktop Screens

I am working with React.js and Tailwind CSS. I have two divs with multiple pictures each. I want to display one on the mobile screen and the other on the desktop and tablet screen. * What would be the preferred way to do that? * Although the first method looks preferable, wouldn't it load the images unnecessarily in both divs if they are needed in only one div at a time? * Method 1:
<>
<div className="block sm:hidden"> {content} </div> // display: block above 640px and display: hidden from 0-640px
<div className="hidden sm:block"> {content} </div> // display: hidden above 640px and display: block from 0-640px
</>
<>
<div className="block sm:hidden"> {content} </div> // display: block above 640px and display: hidden from 0-640px
<div className="hidden sm:block"> {content} </div> // display: hidden above 640px and display: block from 0-640px
</>
* Method 2:
<>
{window.innerWidth > 640 ? (
<div className="block"> {content} </div>
) : (
<div className="block"> {content} </div>
)}
</>
<>
{window.innerWidth > 640 ? (
<div className="block"> {content} </div>
) : (
<div className="block"> {content} </div>
)}
</>
6 Replies
megaByte
megaByte15mo ago
first method is preferred, obviously. I don't think anyone even does Method 2 and if you are worried about unneccesary images loading, just implement lazy loading on your image tags
Joao
Joao15mo ago
I'm not sure if images within display: none elements load, but that's pretty much the approach I'd prefer.
megaByte
megaByte15mo ago
they are loaded i.e. the browser does fetch them from whatever src you've set, but not rendered in the browser
Jochem
Jochem15mo ago
just tested, and they are loaded if the parent div is set to display: hidden;. Adding loading="lazy" to the img tag makes it so that it isn't loaded with display hidden. that said, the prefered solution is the third one: using the picture element and responsive design to use the same div and images regardless of screen size that way, the browser chooses the most appropriate image to display and only loads that one, and you're not duplicating potentially a lot of HTML to send to the client
ABUL KALAM
ABUL KALAM15mo ago
Thank you all
Want results from more Discord servers?
Add your server