Grow your CSS skills. Land your dream job.

Preloading background images that are in an inline style

  • # January 10, 2013 at 1:51 am

    Hey all,

    new problem ahead. I have a wordpress site in development which uses a fullscreen background image on each post. you can see the mockup here: [Tingeltangel](http://tingeltangel.megavillain.org/ “”)

    The Fullscreen image is a fairly large image so it makes sense to show a preloader until its loaded. Now there are a lot of jquery and css preloader scripts out there which work fantastic, as long as the image is in an html img tag or defined in the css file. But since i have images put in dynamically by wordpress i am forced to use an inline style. In my case it looks like this:

    if ( $image_src = wp_get_attachment_image_src( $thumbnail_id, ‘normal-bg’ ) )
    printf( ‘ style=”background-image: url(%s);”‘, $image_src[0] );}?>>

    I tried to adapt the code of this [tutorial](http://jqueryfordesigners.com/image-loading/ “”) to match my case but to no avail. Is there a way to get this working right?

    # January 10, 2013 at 2:42 am

    Whether the image is in the HTML or not, what the browser checks is the URL of the image and see whether it is already loaded or not. Try using one of the tricks here (http://stackoverflow.com/questions/476679/preloading-images-with-jquery) loading all the background images one by one.

    # January 10, 2013 at 7:45 am

    Maybe you need to set a fake attribute to store the background like this:

    <div class="preload" id="main"<?php if ( $thumbnail_id = get_post_thumbnail_id() ) {
    if ( $image_src = wp_get_attachment_image_src( $thumbnail_id, 'normal-bg' ) )
    printf( ' data-background="background-image: url(%s);"', $image_src[0] );}?>>

    Then, with JQuery you set a new `style` attribute with the value taken from `data-background` attribute value:

    $('.preload').each(function() {
    $(this).attr('style', $(this).data('background'));
    });
    # January 10, 2013 at 8:58 am

    Try this one http://www.visibilityinherit.com/code/loading-gif.php

    # January 10, 2013 at 8:44 pm

    Oh, so you want a loading animation when the background is loading. Just add a new markup for the loading animation:

    <div class='loading-bg'>
    <div style='background-image:...'></div>
    </div>
    .loading-bg {
    background:white url('loading.gif') no-repeat 50% 50%;
    }
    # January 11, 2013 at 2:40 am

    Thanks for your replies guys!

    @Hompimpa: mhhh it doesn’t seem to work. The images don’t show up any more when i change ‘style’ to ‘data-background’. Maybe WP don’t like messing with this output?

    # January 15, 2013 at 1:33 am

    I tried to direct another script to the style attribute but to no avail :(

    Anybody got a clue what’s the problem here?

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".