Background instead of inline images for mobile optimization with media queries? - javascript

Ive mobile optimised my site with media queries. Everything looks how I would like it to but unnecessary images (as they're hidden with css) are being downloaded, slowing page loading times.
The easiest solution to this seems to be to replace as many inline images as I can with divs with background images. Then I can hide the div's with media query css for the mobile version.
I know there are potential downsides to this, outlined well in this post:
When to use IMG vs. CSS background-image?
So the company logo, pictures of staff, etc will stay as inline images.
Are there any issues to my approach I havn't considered? Ive read a lot about mobile optimisation, particularly with media queries, and I havn't heard of anyone doing this even though it seems quite an obvious solution where images could be inline or background.
Note, ive done some experiments with iPhones and Android (im waiting to get some Blackberrys) and I know to stop background images downloading I need to set display none to the div's parent, not the div with the background image itself.
Note2, in an ideal world sites would probably have been built as mobile first but in this situation (and often in others) there is a limit to how much the original site can be modified.
Thanks

Unfortunately, there are no great answers for the problems you’re trying to solve.
First, you have the option of moving everything from img tags to css background images. As you note, you have to be careful of losing semantic meaning by doing so.
But even if you can move to background images without losing semantic value, it is still not going to be 100% reliable. I wrote a series of tests last summer. I retested them last week in preparation for the chapter in our book on mobile first responsive web design. The tests are located at http://www.cloudfour.com/examples/mediaqueries/image-test/.
Unfortunately, Android fails every one of those techniques. You can see it downloading multiple copies of the image files via Blaze’s mobile test:
www.blaze.io/mobile/result/?testid=111031_96_316
UPDATE 3 Nov 2011: I’m currently trying to reconcile inconsistent results between what I see on Blaze and what I see using the same device in person. On my local Nexus S, it passes the fifth css test which limits the imgs by putting them inside the media queries. I watched the apache logs and confirmed the device only downloads one image instead of two for test 5. Blaze is running 2.3.3. My phone is running 2.3.6.
This is true for Android 2.2, 2.3 and 3.0. Hopefully, 4.0 will incorporate the webkit fixes that prevent this behavior:
bugs.webkit.org/show_bug.cgi?id=24223
BTW, this seems to conflict with your comment about testing setting the parent div to display:none on Android. If you’re getting different results, I’d love to hear about it.
If you keep them as img tags, what are your options? On this topic, I have written a multi-part series. The second part in the series provides an in-depth look at the different techniques:
http://www.cloudfour.com/responsive-imgs-part-2/
Again, none of the solutions are great. If you want something that is simple and will work most of the time, I’d go for adaptive-images.com. Or route images through Sencha.io SRC until we have a better solution for this problem.
BTW, sorry for having so many links that aren’t actually links. This is my first response on stackoverflow and it will only allow me to include two links.

Why not do a mobile first approach and then use media queries to enhance bigger screens.
Also you can use media queries to serve specific CSS files.
With the inline images I have tried a script block in the head and immediately after the opening body tag, which runs only for mobile devices (detect via classname added to body, or presence of a media query CSS file) that find all inline images with a certain class and empty the src attribute.
see here Prevent images from loading
<script type="text/javascript" charset="utf-8">
    $(document).ready( function() { $("img").removeAttr("src"); } );
</script>
another way is to use url re-writing with mod rewrite and .htaccess or url rewrite module for iis. redirect user agent strings for mobiles to a small blank image.
see:
A way to prevent a mobile browser from downloading and displaying images
RewriteCond %{HTTP_USER_AGENT} (nokia¦symbian¦iphone¦blackberry) [NC]
RewriteCond %{REQUEST_URI} !^/images/$
RewriteRule (.*) /blank.jpg [L]
you can improve the above by loading your inline images from a different sub-domain and rewriting only those for mobile, as you don't want to rewrite all images (logo etc.)

If I'm understanding your question correctly, this seems like a perfect use case for srcset and sizes. This MDN article is a great post for learning the concept in-depth, but I will also summarize here. Here is a full, kind of complicated example:
<img srcset="elva-fairy-320w.jpg 320w,
elva-fairy-480w.jpg 480w,
elva-fairy-800w.jpg 800w"
sizes="(max-width: 320px) 280px,
(max-width: 480px) 440px,
800px"
src="elva-fairy-800w.jpg"
alt="Elva dressed as a fairy">
This code says:
If my browser doesn't support srcset use what is in src by default. Don't leave this out.
Hey browser, in srcset, here are 3 files and their natural widths separated by commas.
Hey browser, in sizes here are the widths of the space I want my image to take up depending on the media query. Use the one that matches first.
Then the browser itself will calculate which is the best image to use based on size AND screen resolution of the user then ONLY downloads that one which is pretty awesome in my book.

Ok, important thing to note is that mobile != low bandwidth != small screen and desktop != high bandwidth != large screen.
What you probably want is to make a decision based on client bandwidth and client screen size. Media queries only help with the latter.
David Calhoun has a great writeup on how to do this here: http://davidbcalhoun.com/2011/mobile-performance-manifesto
Highly recommended.

I stumbled recently on a great blog article on the subject, adressing the problem of responsive images (ie serving smaller images on smaller devices). The comments of the article are the most interesting part, and I think the replacement technique coined by Weston Ruter is a promising one :
http://jsbin.com/ugodu3/13/edit#javascript,html,live
(look at the other iterations in the comments).
It has lots of caveat (and is maybe difficult, but not impossible, to merge in an existing website, as the affect all your non absolute links, not only imgs), but I will try it (merged with a lazy loading) on my next project, which is a responsive website that my designer made quite heavy (and he does not want to make it lighter). Note that you could combine this to a php script resizing the images on demand if your server supports it.
The others common solutions for responsive imgs are cookie based (check Filament Group Responsive images plugin).
I prefer responsive images to css background because they're more correct semantically and parse-able SEO-wise. If I agree that we should not assume that bigger screen = more bandwidth, we lacks tools to address this (navigator.connection is Android only.) so assuming that most mobile users have a crappy 2G/3G connection is the safest way.

I'm not sure if you have thought about doing this but one of the things you can do is check for the width of the screen resolution with javascript and then if the resolution is less than some number (I use 480 because at that point that site looks bad) then switch the css templates from the default to the mobile themed template.
function alertSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
}
if (myWidth < 48)
{
switch css template to mobile template
}
}

Adapting to an existing site sucks but we do what me must. Here is how I solved it when importing a blog's feed into a mobile site. It scales the existing image on the page to the page's width ONLY if it's larger than the screen.
var $images = $("img[width]");
$images.each(function(){
try{
var $image = $(this);
var currentWidth = Number($image.attr("width"));
if(currentWidth > screen.width){
$image.width("100%");
$image.removeAttr("height");
}
}
catch(e)
{/*alert("image scale fail\n"+e)*/}
});
By making the width 100% and removing any height attribute, the image will scale perfectly to take up the full width whether you're in landscape or portrait orientation.
Chances are, the images on your regular site are already web optimized. There's usually not that much performance boost to be gained by loading smaller images. Reducing HTTP requests will make much more of a performance boost than bringing over smaller images. It may not be the perfect solution but it is certainly going to be the least maintenance. If you can't reasonably control what images are going to be used on the site, this is a pretty reasonable solution. If nothing else, maybe this will spark another idea for you.

Related

Site not loading properly on mobile

I am having issues trying to load my site, http://www.internhacks.io/, on any mobile browser.
The project can be found here on Github.
I have tested the site on mobile using Chrome dev tools, and everything loads fine/acts responsively.
However, when testing the site on my actual phone, sometimes the site does not load at all, sometimes only partially.
Note: the apply button is not meant to do anything yet
I think it may have to do with having a large image as the background. Should I be serving a smaller version if detecting the window is smaller? The img height is set to 100vh.
If anyone knows what might be causing this, or knows of a better way to debug the site on mobile than in Chrome dev tools, please let me know!
I use Opera mini to test mobile devices (aka android) with various screen resolutions.
"height is set to 100vh" huh? never saw that one before. To fit graphics within space available, avoid fixed sizes (aka 100px) and I use relative width:xx%
YES, it's wasteful to send large graphics to a mobile device and from the server, you need to send some xxx-low-res.img instead
it's helpful to load JS scripts into a section to allow all objects to be loaded first.
I think your main issues is that the big images should use smaller, light-weight pictures instead since it'll speed up the resize process when rendering on the phone. Other than that, you want to stick away from, as #jobeard mentioned, from using fixed sizes like the 100vh and use a relative width such as 10%.

Methods to get the screen resolution before a web page is getting loaded

I want to know the different methods to recognize the screen resolution.
Like
Desktop Resolutions
Tablet Resolutions
Mobile Phones etc;
Starters... You can't execute any query or anything without your page being loaded. Aside that, there are several ways you can check your screen resolutions. You could use the CSS media queries or JavaScript.
See the links below for more insight.
http://css-tricks.com/resolution-specific-stylesheets/
http://www.w3.org/TR/css3-mediaqueries/
There are other available resources online so just make some extra searches and you'll be good to go.

How to prevent images from loading on devices of certain width?

I don't want to set them to display:none; with media queries because they would still load. Is there any way to load them only if the device's width is over 500px for example?
You could load them all after the page itself has loaded using javascript, and ignore certain images if window.innerWidth is less than 500.
The specifics of the implementation would be determined by your own application, but I would recommend something like the following:
Replace all images with placeholders, and give the ones you may wish to hide a certain class:
<img src="placeholder.png" class="gt500" data-source="realimage.png">
You could then do something like (assuming jQuery):
$(document).ready(function(){
if(window.innerWidth > 500) { return; }
$('img.gt500').each(function() {
$(this).attr('src', $(this).data('source'));
});
});
Which will swap all the placeholders for the real images, but only if the window is wide enough.
I'd try something like this:
<img src="" data="actualimagesource" />
Check each image, either on the server or client side: If the site's width allows the image to display, pull the string from "data" and place it in the "src" attribute.
Very similar to: http://www.appelsiini.net/projects/lazyload
You can't prevent an image from loading except to delete it from the DOM or change it's src. Even then, it'll already have started loading, so whether it loads in full will depend on how the browser implements it, and I don't know the answer to that.
All I can suggest is that you prefix all the image srcs with a #, then do something like this:
var imgs = document.querySelectorAll('img[src^="#"]');
for (var i = 0; i < imgs.length; i++) {
imgs[i].setAttribute('src', imgs[i].getAttribute('src').substr(0));
}
if the screen width is greater than a certain number. That prevents users who have JavaScript disabled from seeing your images though, so consider the pros and cons carefully.
I'd probably do this server-side. WURFL is a database that's often used for mobile device sniffing, a PHP example is here. In desktop web development browser and device sniffing is considered super bad practice. For mobile, because of the sheer number of devices and their different capabilities it's often a necessity. I believe WURFL tests the user agent string server side (amongst other things) to detect the device and will then return a bunch of information about it (including screen resolution) you could then serve different sized images based on this information.
I don't think there's a way of cleanly preventing image load at the front-end. You could loop through all images with javascript on document load and set the src attribute to an empty string if their width was greater than 500px. The problem with this is that you'd have to make sure that all your images had specific dimensions in the markup and even then some browsers won't report the width until the image has finished loading. You also couldn't guarantee that images wouldn't start download before the javascript kicked in (and not all mobile devices support js or have it turned on) This feels horribly hacky to me though.

best method of detecting mobile browsers with javascript/jquery?

For a site I'm working on I'm implementing image preloading with javascript however i most certainly do not want to call my preload_images() function if someone is on slow bandwidth.
For my market the only people with slow bandwidth are those using mobile internet on a smartphone.
What's the best approach for detecting these users so i can avoid image preloading for them?
option 1 : detect browser width
if($(window).width() > 960){ preload... }
option 2: detect user-agent with a list of browser to preload for
if($.browser in array safelist){ preload... }
are there any better options?
I find that I dislike sites that decide which version of the site I should access on a particular device or environment. It's great to make an initial decision based on whatever criteria you settle on, but for goodness sake, give me a link I can click so I can choose the "Higher Bandwidth Site" or vice versa and save it to a cookie. Then I can override any error the automated script makes with my own judgement.
Maybe using the CSS #media directive, along with hidden objects?
.imagesToPreload {display:none;}
#media screen {
#imageToPreload1 {background-image:url('blah.img');}
}
#media handheld {
#imageToPreload1 {background-image:none;}
}
Then in Javascript, you can fetch all objects in "imagesToPreload" class, read the backgroundImage property and preload it if its not none.
Admittedly, this is off the top of my head, I didn't test this idea. As usual, there must be something I am not thinking about...
I think edeverett's point about mobile not necessarily being slow (and similarly desktop not necessarily being fast) is a good one.
Remember not to remove choice for your visitors - i.e. most decent mobile browsers have an option not to load images (or specifically not to load large ones) and also avail of proxy services that compress images before downloading - some mobile visitors may want the full preloaded experience on your site.
Another solution might be something like:
if($(window).width() < 320){ preload_smaller_images(); }
There's less reason than there used to for the mobile browsing experience to be more limited than that of the desktop.
R. Hill's CSS suggestion is not the worst though (if it can be done in CSS, it should imo), it can also be done per-screen-size:
#media handheld, screen and (max-width: 320px){ /* */ }

Can I zoom into a web page like IE or Firefox do, using programming?

Simple - I have a layout that is 800 by 600. When I press Ctrl and +, it zooms in and looks wonderful.
I want to know if there's a CSS/Javascript way to do the same? Without the user having to do it (because users will not do it and see the small layout).
Same question was posted by someone Setting IE "Optical Zoom" feature using Javascript/CSS that got no good replies.
There is a zoom CSS property, but it is part of CSS3 and is most likely not widely supported. By setting this on the body element using JavaScript you can zoom the entire page.
I would agree with the sentiments of the answers to the question you linked to though in that it should be up to the user to choose their own zoom settings. If your site is too big/small to see, it indicates a problem with your site design.
You can set all sizes as dynamic (use em for fonts, % for divs/images sizes). Then change the main wrapper and the main font size using javascript.
You can also use CSS switching. Put all the colors and such in one css file. Then create 3 or 4 levels of zoom and inside hardcode different sizes for all the existing classes.
Example:
main.css
a{color:red;}
small.css
a{font-size:10px;}
medium.css
a{font-size:12px;}
Not all designs (in fact I'd wager, none, without targeted style sheets) can cope with the vastly different sizes of screen out there today, from portrait orientated screens at public libraries, to ultra fine artworking Macs with giant landscape screens and tiny little laptops - the latter two often used by executives that have NO understanding of how the zoom features in a browser work and also often have terrible eye sight and little patience.
My suggestion is to use relative sizing like Marcgg suggests. If you're really looking to be super flexible the you could use javascript or browserhawk (or equivalent) to measure the screen sizes and switch out style sheets for those that are really not going to work with your layout.

Categories