treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Preloading background images that are in an inline style

  • 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

    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:

          <div id="main"<?php if ( $thumbnail_id = get_post_thumbnail_id() ) {
          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 to match my case but to no avail. Is there a way to get this working right?

  • 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.

  • 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'));
    });
  • 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%;
    }
  • 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?

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

    Anybody got a clue what's the problem here?