Most efficient position for background-image property in a style sheet - css

I am placing a large, non-repeating background image on my website using the CSS background property. Since the image is so large, it takes a long time for some connections to render the image.
Here is my CSS:
#wrapper {
background: url('large-image.jpg) no-repeat center center;
}
I have already done the following to optimize the image for the web:
Reduced it to the lowest possible resolution that does not compromise quality
Changed the image type from a PNG to a JPEG
Styled the page so that the content is readable even without the background image
My question: To further optimize the image loading time, would it make a difference if I put the background tag at the bottom of my style sheet? Or would the effect of this be negligible?
I tend to order my CSS by the hierarchy of my HTML, so the #wrapper styles are at the top of my style sheet. Does the order of properties in a style sheet make a noticeable impact on load time when the user has a slower connection?

Location in the stylesheet will not affect the load time.
What you can do though is prevent it loading in some cases, such as on a cellphone.
For reference:
http://css-tricks.com/snippets/css/media-queries-for-standard-devices/
Those media queries aren't fail-proof, but they'll catch alot of the slower cases, which would generally be mobile devices. On the other hand, if somebody is on a 56k modem with their desktop, I just don't know what to do about it (maybe they're used to it).
You can use Jquery and waitforimages to ensure it loads after all other images, if you wish.

What could affect perceived loading time is initial #wrapper availability - i.e. if at the time of the initial load it is not part of the page and is added with JS, the background image will not begin loading - but I doubt this would be a common scenario.
Background image loading does not affect domready handlers, however if you want to speed up background availability you could try the following:
#wrapper {
background: url(large-image.png) no-repeat center center,
url(small-image.png) no-repeat center center;
}
From mdn:
With CSS3, you can apply multiple backgrounds to elements. These are
layered atop one another with the first background you provide on top
and the last background listed in the back. Only the last background
can include a background color.
What this does is effectively allows you to load a lower-res image as the bottom layer of the background, while the expensive hi-res image is still loading. Remember the good old times of lowsrc? That's the behaviour we're simulating. Note that both the low- and the hi-res image downloads begin simultaneously, so use this only if the large image is truly unbearably large.
Also: you're saying you've optimized the image; I still suggest you try Yahoo SmushIt, you'd be surprised how muich redundant data can be stripped from a PNG witout loss of quality (I currently have intermittent problems using their service, but it works after a few attempts, alternatively you could use OptiPNG but imo it would be too much effort to set it up and configure for a single image)
Update:
It has been suggested you wait for domready to fire and add your style using $("#wrapper").css(...);. What that does is add inline styling to an element, which would 1) interfere with selector specificity 2) only apply to this particular instance of #wrapper (bad if, say, it is part of ajax content coming from the server).
You could alternatively add a new css rule at runtime:
$('head').append('<style type="text/css">#wrapper {background: url(large-image.jpg) no-repeat center center;}</style>');
This would be organically added to document stylesheets and apply to all future instances of #wrapper, as well as not interfere with selector specificity. You still end up with a brief flash of unstyled content (before the handler is fired and the style is applied) so I don't advocate this approach.

See this previous question. The CSS stylesheet will be fully loaded and evaluated before the page is shown, so the location of your background-image CSS does not matter in the stylesheet.
If you want the image to only load once the rest of the content is displayed you could use jQuery:
$(window).load(function(){
$("#wrapper").css({'background-image':'url("large-image.jpg")', 'background-repeat':'no-repeat', 'background-position':'center center'});
});

Related

Any benefit to loading a single image via background with CSS?

Ok, obviously if you have a lot if icons you generally load them in via a background image so you can utilise sprites; however, I was just wondering if there is any advantage to loading them in via the background versus loading them via a img tag when it is just a single image?
Does the one in the CSS still make a http request for the image?
Sounds like you're mostly interested in how this affects performance. But since the question is open-ended here are other reasons, for completeness:
If you need to calculate the image's height based on its width (a common responsive design method is width: [something > 0]; height: 0; padding-bottom: [some]% )
If you need to use CSS to swap out the image (basic icon example: if the image changes on :hover and you aren't using a sprite, for any number of reasons)
If you need to be able to use CSS background options like background-size or background-position (IE > 8)
If you need to have HTML on top of your image without adding an additional element
If you need to use pseudoelements like :before and :after, which are not supported for <img> (not required to be supported, anyway)
Yes, it still makes a request, unless you URL encode the image, but this you can also do inline and is not necessarily more performant.

How bad is to store all background images in CSS?

I have created the layout of the website (template). I used Photoshop to design the picture and sliced it to create the divs. It gave me an HTML file including the HTML and CSS code. I separated these in two files HTML and CSS. The background images were being called inside the <div id="idName"> tags as <img src=... tags. I changed this. I loaded the images in the CSS file as
idName { background-image: url(URL); }
All the images in the site are loaded like this creating the background as a whole.
Now my question is: Is this a bad practice? because if I leave the images inside the <div> tags I wont be able to put my content on top of the image. With the background-image attribute in the css file I can put my content anywhere, not having to worry about the background.
No, this is perfectly fine, and actually may be a best practice for background images. Moving the image declarations into the style sheet means the images may be downloaded a little bit later, but most browsers should have enough other resources to load in the meantime, and you'll want prioritize HTML and stylesheets before background images anyways.
Just don't use CSS backgrounds for actual images: If the fallback background color would significantly change the meaning (i.e. the image is content), you should use <img> elements with an alt= attribute. If you're not sure whether this is a good idea, consider this question.
To increase performance (by reducing the number of HTTP requests), you may want to consider using CSS sprites.

How do you add a background image for printing in IE/FF?

In other topics I've found that IE/FF doesn't print background images by default. Now that's a shame, because background images add some possibilities that are very difficult to reproduce with classical <img> tags:
You can align them both horizontally and vertically
You can crop them if they are larger than the target element (which also enables the idea of CSS sprites)
Now, it's not impossible to do, but it will require me to have different HTML layouts for printing and normal page, and the printing layout will be quite overcomplicated (since I'll have to use <table>s to achieve vertical alignment). Also, the benefits of CSS sprites will be lost.
Is there any hope? I gather that #media print doesn't help, but isn't there something else, maybe browser-specific, that would allow one to say: "Yes, this isn't a normal background, it really needs to be there even in print view"?
Not possible. You would have to some how convert your background images to img or use Canvas. Of course using canvas depends on which IE you supporting.
Its a browser setting which restricts the printing of background images. I think the logic behind it was that the vendors wanted to give the users the option of printing background images and ensure that the web developer could not alter these settings through some sort of script.
As a general rule, background images should be reserved for adding to the page design but aren't essential to understanding the content. Therefore it shouldn't matter if they are missing when the page is printed. If something (such as a product shot) is important, then it should be included as an actual image (which has the added bonus of being more accessible).
Could you look at including the image, then hiding it using CSS and duplicating is as a background image (perhaps dynamically using JS)? That way, you can ensure the image itself shows in your print stylesheet, and you get the benefits that having a background image brings. I've created a very simple example here.

CSS Spritesheets

I've just started using CSS spritesheets to significantly reduce the number of requests a user makes on our webserver (previously I had designed a page with 200 thumbnails, each linked separately, so that was 200 requests just for those and didn't know it was an issue until someone told me about it)
After going through w3schools I have figured out how to use it and have downloaded spritesheetpacker to help me make the spritesheet as well as give me the dimensions and offsets.
Now I have a CSS file that's extremely long, and am not looking forward to tagging 200 HTML elements manually. Is there a different way to deal with this situation? Here are some details:
I am familiar with javascript (not much JQuery though)
I have all of the dimensions and offsets for the images from the packer.
The page contains a table with a column for thumbnails, and another column with a link to the file associated with it, so people can quickly scroll through the page and pick what they want. You can also click on the thumbnail to see a full-size picture
I am currently displaying the image using the img tag and wrapping them with anchors, where the img class is just the picture filename (since it is also included with the output from the packer)
You can save a bit of CSS by grouping things together with similar dimensions and then just coding the background images.
<a class="buttonA Image5"></a>
.buttonA {
width:100px;
height:30px;
display:block;
}
.image5 {
background-image:url(...);
background-position:....
}
If you use display:block on your anchors, you can use a CSS background on it and eliminate the image tag completely.

background-image load or display delays even though cached in IE7

I have a seperator li which has a background image, in an expanded tree menu, it may appear several times using the css:
.simpleTree .line {
background:url("/images/Css/gridLine.gif") no-repeat 0 0;
Even tho it is cached (from previous instances), there is still a slight delay in IE7 (~500 - 1sec) before all the background images fires up. Is there a better way to do this or make it quicker?
As far as I can tell the delay shouldn't be because of a single gif image. Check your site with YSlow or PageSpeed. Maybe some other content is blocking your image to appear fast (like javascript execution).
There are some things that you can try. You can try to reduce the size of your image and than in the CSS use the TAG "repeat-x" or "repeat-y".
In some cases, .gif's are not the best type to display images, you can try saving your image in diferent formats and see if they get smaller.
Best Regards

Resources