Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent image from loading on mobile devices

To maximize efficiency for mobile devices, I would rather not have images that are used for the desktop version. Through research, I have learned that simply using display:none; css or jQuery('img').hide() will only hide the image, but still use the resources to load it.

How can I take this:

<div class="com_router_img">
<img src="http://www.example.com/wp-content/uploads/2013/05/img.jpg"
 alt="img" width="700" height="350" class="aligncenter size-full wp-image-307" />
</div>

And NOT display it on my mobile stylesheet? Here is mobile stylesheet query:

<link rel="stylesheet" media='screen and
 (-webkit-min-device-pixel-ratio: 1.4) and (-webkit-max-device-pixel-ratio: 1.5)'
 href="<?php bloginfo('template_url'); ?>/smallphone.css" />
like image 476
Chris Avatar asked Mar 22 '23 09:03

Chris


2 Answers

It is common practice to use images as background images through CSS when this level of optimisation is required. A mobile browser will only load the CSS that it applies to it.

CSS

<style>
@media (max-width:600px) {
   .image {
      display:none;
   }
}
@media (min-width:601px) {
   .image {
      background-image: url(http://www.example.com/wp-content/uploads/2013/05/img.jpg);
      width:700px;
      height:350px;
   }
}
</style>

HTML

<div class="image">

</div>
like image 192
Kevin Lynch Avatar answered Mar 27 '23 09:03

Kevin Lynch


There are multiple approaches to this. Personally I like the technique they use here: http://adaptive-images.com/

It keeps your code simple and the HTML semantically correct

You could also write your own js solution.

Your HTML could look something like this:

<img alt='some image' src='blank.gif' data-src-mobile='my-mobile-version.jpg' data-src-desktop='my-desktop-version.jpg />

The blank.gif would be a 1px transparent gif. With javascript you could detect wether on mobile, and then replace the src atribute with the appropriate data-src attribute.

This should be an easy solution, but it will require your js to ru before the images start loading, and technically speeking it is not semantically correct. Also search engines will have troubles indexing your images.

like image 21
Pevara Avatar answered Mar 27 '23 11:03

Pevara