6

I'm retrofitting an adaptive layout to an existing site. Basically at 500px the site changes to a 100% width mobile style layout. Normally I'd use ems, but as I say, I'm retrofitting.

I know how to load js and css conditionally, but how about html and images?

On the homepage of the site there is a large image that fills the screen, I don't need it on my small screen layout, so I want it to load in if the browser is wider than 500px. Trouble is I can't store the <img src="..." /> etc in js because it's dynamically loaded with php. The client controls the images through wordpress admin.

Any thoughts would be appreciated. Thanks

5 Answers 5

3

I would suggest, if you can, to use divs and set the background-image property to the image you need. You can target the screen size using media queries. Basically...

HTML
<div id="splash-image"></div>

CSS
#splash-image {
    background-image: url("small-image.png");
}

@media only screen and (min-width: 500px) {
    #splash-image {
        background-image: url("big-image.png");
    }
}
2
  • Hi, yeah that would be the ideal, but it's a content managed image. I've wrapped the image together with php inside some js checking for browser width (see comment above). It seems ok..
    – Geoff
    Jun 22, 2013 at 11:43
  • This will still load both background images. Apr 29, 2014 at 18:04
1

This will work for one or two things. For site-wide image loading preferences, there are other solutions.

See this codepen for an example. I have checked it in dev tools to be sure that the large image doesn't load.

So, you find the window-width with .width() and store that in variable called (whatever you want) I called it wWidth. Then an if statement. if the window-width is larger than 1200px (It sucks you can't use em) --- THEN, load this image - otherwise, load this smaller image. To get it into the DOM, you append the html to an existing div with .appendTo()

$(function () {
    var wWidth = $(window).width();
    if (wWidth > 1200) {
        $('<img alt="larger image" src="http://placehold.it/1200/1200"/>').appendTo('.sidebar');
        $('.sidebar a').hide();

    } else {
        $('<img alt="smaller image" src="http://placehold.it/600/600" />').appendTo('.sidebar');
    }
});

This example was for a map... so If they wanted to load the google map, I had a link there they could press to load the nicer map. (but then, if the the window was large, I wouldn't need that link - so I hid it with .hide()

EDIT 04/2014

As of April 2014, I've been switching the src with attr() so this way, you just have your image for mobile, and then if it's a big screen you can insert the larger image's source... but then you load 2 images... so you could instead, load a 1px x 1px blank gif or something to start... and give it a width and height near the ratio you are going for...

a new CodePen here:

HTML

<div class='image-w thing' id='target01'>
  <!-- standard image for small screens or a blank gif or something -->
  <img src='http://placehold.it/640x640&text=Default-image' alt='' />
</div>

jQuery

var imageSizeThing = function() {

  var windowWidth = $(window).width();

  if ( windowWidth < 501 ) {

    // if you start with a blank gif or something
    $('#target01 img').attr('src','http://placehold.it/640x640&text=Default-image');

  } if ( windowWidth > 500 ) {

    $('#target01 img').attr('src','http://placehold.it/1000x1000');

  } if ( windowWidth > 900 ) {

    $('#target01 img').attr('src','http://placehold.it/1800x1800');

  } if ( windowWidth > 1200 ) {

    $('#target01 img').attr('src','http://placehold.it/2400x2400');

  }

};

// call it on DOM ready, and if it makes sense, when the window resizes
$(document).ready(imageSizeThing);

$(window).resize(imageSizeThing); 
2
  • Should there maybe be a <noscript> fallback?
    – silvenon
    Dec 22, 2014 at 19:52
  • 1
    I would say no. With all the js and angular etc... - javascript is just the norm for 2015 and on. - (for me) Dec 24, 2014 at 1:44
1

You can set the display of the image based on media query(but it will load anyways)

@media screen and ( min-width: 500px ) {
    #image-id {
        display: block;
    }
}

Or, to not allow the image to load at all for smaller screens, you can wrap the image inside a div(say, with id img-container) and do the following:

if(screen.width>500){
    document.getElementById('img-container').innerHTML = "<img src='image_source_url' />";
}
5
  • this is called conditional displaying instead of loading Jun 22, 2013 at 9:59
  • Thanks @ManishJain, I don't want the image to load on small screens, and the trouble with the js solution is that the image displayed randomly with php. I'm assuming you can's have php inside javascript? the code for the image is this: <img class="<?php echo 'aligncenter size-full '.$imgInfo[$randno][id];?>" src="<?php echo $imgInfo[$randno][src];?>" title="<?php echo $imgInfo[$randno][title];?>" alt="<?php echo $imgInfo[$randno][alt];?>" />
    – Geoff
    Jun 22, 2013 at 11:18
  • 1
    This seems to work <script> if (document.documentElement.clientWidth > 940) { document.write('<img class="<?php echo "ligncenter size-full ".$imgInfo[$randno][id];?>" src="<?php echo $imgInfo[$randno][src];?>" title="<?php echo $imgInfo[$randno][title];?>" alt="<?php echo $imgInfo[$randno][alt];?>" />'); } </script>
    – Geoff
    Jun 22, 2013 at 11:34
  • Does that seem viable? Obviously I'll change the 940 to 500
    – Geoff
    Jun 22, 2013 at 11:37
  • 1
    @Geoff Of course, you can have php code inside javascript code(whether it comes under best practices or not is a different issue), the only point to keep in mind here is, the php code will be compiled from server and sent to browser after that. So, when your browser would render your page, it will be seeing only javascript and html. Jun 22, 2013 at 18:20
0
image.load([{

    // Test if media query matches
    test : image.mq('only screen and (max-width: 600px)'),

    // load css and js purely for mobile
    yep: ['/assets/mobile.css', '/assets/mobile.js']

  }]);
1
  • Is this a Modernizr method? Apr 29, 2014 at 18:06
0

The question is old but I had the same issue and thought of writing my solutions for others that might be interested.

Client side only with angular js

At the client side, you "discover" the "type" of resources that should be loaded. For instance, in main app controller:

$scope.type = (screen.width > 500) ? 'desktop' : 'mobile';
// or window.navigator

Then in content that you want to display conditionally, you add the variable

<img src="images/{{type}}/foo.jpg">

Note: that the place where you put your controller matters. If it is before the </body> tag, the browser will make a request before angular expands the variable. If it's in ´`, then the variable is expanded before the browser makes the request

Server side only (PHP)

You can use $_SERVER['HTTP_USER_AGENT']; to detect if it's a mobile device and act accordingly.

Obviously user agents can be spoofed but since the only difference is the image size, the worst it can happen is you serving a small image on a big screen or vice versa.

For instance:

$useragent=$_SERVER['HTTP_USER_AGENT'];

if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))) {
  $type = 'mobile';
} else {
  $type = 'desktop';
}

Then serve the image accordingly to $type

Mixed

You can also mix the two, specially if you're more interested in the screen size (or other property of the browser) than the actual user agent. I use the following strategy a lot.

  1. Create a landing page (with a splashscreen or something) that sets a cookie.

    var type = (screen.width > 500) ? 'desktop' : 'mobile';
    document.cookie = 'type=' + type + '; expires=Fri, 31 Dez 2020 00:00:00 UTC; path=/';
    
  2. Then redirect the user to the main page

  3. Then use the cookie server side to display the correct images

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.