Tuesday, May 3, 2011

CSS Background Image Load Behavior

Say there is a css style declaration to an element which has been set display:none (not displayed on screen) and it also has a background image set.

Lets say this element is displayed on an event such as a mouse click. Would the browser load these images even before the element is displayed? Is this load behaviour consistent across browsers?

From stackoverflow
  • It is not loaded automatically but you can use a Javascript trick to preload an image.

    pic = new Image(); 
    pic.src="http://url/imagetoload.png";
    

    As a better solution, you may create a div with a negative positioning value (such as left: -1000px) and assign imagetoload.png to its background to load the image.

    yfel : thanks,vote for your first answer in this site ^^
  • No, browsers I've tested before do not.

    if you do want to load the image, try using background-position: -1000px -1000px which does work. It won't show the image, but it will be preloaded. However, the element will be in the normal flow, i.e. not hidden.

    yfel : i just want to make sure that images which are hidden from the document are not loaded by the browser.So this is ture for major browsers?
    alex : Yes, if a background image is on a hidden element, it won't be shown. However, if you delay hiding an element with JS for example, there's a chance that image will be loaded.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.