Steer clear of downloading images while on your smartphone

As I develop a responsive website, I encounter the challenge of optimizing image loading based on viewport size. While using CSS to hide images not needed for certain viewports can reduce display clutter, it does not prevent those images from being downloaded by the browser due to HTML parsing before layout rendering.

To address this issue, I explored the use of the <picture> element:

<picture>
    <source srcset="image.jpg" media="(min-width: 992px)">
    <img src="" alt="an image">
</picture>

This method ensures that the image is not downloaded if the window width is less than 992px. However, Safari's lack of support for this feature poses limitations.

In response, I devised a JavaScript/jQuery solution:

I marked each image with attributes specifying the device it should load on:

<img src="" alt="img" data-device="mobile" data-src="img-mobile.jpg">
<img src="" alt="img" data-device="tablet" data-src="img-tablet.jpg">
<img src="" alt="img" data-device="desktop" data-src="img-desktop.jpg">

The JavaScript function below dynamically loads images based on the viewport size:

function loadImages() {
    var mobile = window.innerWidth < 768;
    var tablet = window.innerWidth >= 768 && window.innerWidth < 992;
    var desktop = window.innerWidth >= 992;

    // Image loading logic
}

$(document).ready(function() {
    loadImages();
});

$(window).resize(function() {
    loadImages();
});

This approach optimizes image loading without relying on CSS hacks but may not be ideal in the long run. I am curious how others tackle this issue and what best practices are recommended for handling responsive image loading effectively.

Answer №1

Your suggestion to find a creative solution to the problem is quite impressive. How about considering a different approach: instead of using an img element, you could use a div element with a dynamic background-image loaded through @media styles in CSS for various devices? This way, you can display different images based on the device being used, which is a technique many developers are currently implementing.

I hope this alternative provides some valuable insight for your project!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with hydrating React local storage hook in custom implementation within NextJS

Currently facing an issue while implementing the localstorage hook in NextJS. The error message I am encountering is: Error: Hydration failed because the initial UI does not match what was rendered on the server.. Any suggestions on what might be causing ...

The Protractor element appears to be detached from the page's document

Currently, I am facing a challenge while using protractor in my Angular6 Project. The issue revolves around clicking elements within the project. Situation: Within a table row, there is a list of elements that I need to click on individually. Challenge: ...

Reset the counter variable when a certain condition is met

I am facing an issue with my simple "pagination" counter that fetches the next page from an API. The problem arises when I switch between different categories, such as movies or series, because the counter does not reset. Instead of starting again from the ...

Browsing the web with Internet Explorer and uploading images

I am facing an issue with a large form that contains over 100 submit buttons. The code I am currently using is: <input type='image' src='../images/add.png' name='FormDuplicate' value='" . $resInvoices['iProjectID ...

Achieving uniform row height in CSS Grid Layout

How do I ensure all footers with a green background have the same height, while also keeping the content height consistent? Current result: https://i.sstatic.net/SrgFq.png Desired output: https://i.sstatic.net/4cr25.png CodePen: https://codepen.io/yas ...

There is a space separating the slider image and the navigation bar

Having a small space between the slider image and the navigation bar is causing some issues. I've tried various solutions like minifying the code, adjusting margins, and setting line heights to zero but nothing seems to be working. One question I have ...

what is the process for configuring a Universal link using javascript?

I have taken all the necessary steps to utilize a universal link. I created an AASA file, verified it using aasa-validator, and configured it in XCODE as required. Now, I am facing the challenge of setting up a hyperlink on my webpage that can redirect us ...

What is the best way to include an active CSS class in a menu item?

Link to example Can you figure out why the Home button is not turning red in this code snippet? .navbar a:hover, .navbar a:focus, .navbar a:active { color: red !important; } <nav class="navbar navbar-expand-lg"> <div class="collapse navbar ...

Achieving two-way data binding in a directive without using an isolated scope

Implementing scope: { ... } in a directive creates an isolated scope that doesn't inherit from its parent. However, my usual practice has been to utilize this for easily declaring HTML attributes with bi-directional data binding: scope: { attr1: ...

Changing base 64 into Mp3 audio format using PHP

I currently have an "audio" tag with a script (which is essentially a plugin) that receives and saves it as base64. This functionality is working properly. My goal now is to modify the script in order to send the base64 data to the server, convert it to m ...

Loading a local CSS file upon opening a tab with a specific URL

When opening a tab to load a local HTML file from an addon (using addon-sdk), the following code is used: tabs.open({ url: self.data.url('index.html'), onReady: myScript }); However, there seems to be no straightforward way to include a CSS ...

What is the best way to keep an image centered in the nav-bar as it decreases in size?

As I work on building a website using a template (https://github.com/learning-zone/web-templates/tree/master/victory-school-free-html5-bootstrap-template), I encountered an issue with the navigation bar. The original design appears like this: Before shrin ...

"Embracing Dynamism: Enhancing Vue3 with Dynamic Routing for

Seeking guidance on implementing a dynamic component with Dynamic Routing in Vue3. The goal is to render a component based on the parameter (path named id) from router.ts. In the router.ts file, there is a dynamic parameter called id that needs to be used ...

I am getting a HTTP 405 error indicating that the method is not allowed, and it appears to

In my Javascript program, I requested this URL using the library epson-2.6.0.js, which is the Epson SDK for JavaScript specifically designed for thermal printers. My target device is a TM U220 connected via ethernet. GET XHR http://192.168.199.15:8008/soc ...

React components multiplying with every click, tripling or even quadrupling in number

My app enables users to create channels/chatrooms for communication. I have implemented a feature where pressing a button triggers the creation of a channel, using the function: onCreateChannel. Upon calling this function, the state of createChannel chan ...

Incorporating words into the core of a pie chart: Highcharts

Is there a way to display the total value in the center of a pie chart? I've attempted some methods but haven't been successful. The goal is to show the sum of all y values. Input export const data = [ { y: 15, name: "Category 1&q ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

What's the reason behind CSS transitions starting with a black background?

When I apply a transition to the heart, it inexplicably turns black at the start of the animation before displaying the intended gradient effect. Below is the code snippet: .heart { font-size: 2.5rem; padding-right: 2rem; } .heart:hover ...

Using the react-router Navigate component within a Next.js application allows for seamless

Is there a way to achieve the same result as the Navigate component in react-router within Nextjs? The next/Router option is available, but I am looking for a way to navigate by returning a component instead. I need to redirect the page without using rout ...

Issue with strange behavior of CSS cursor with images

Is there something blatantly obvious that I'm missing here? My goal is to replace the cursor css property with a png, as shown in this example here I was able to get it working with the 'happy.png' demo, but for some reason it won't wo ...