2

How do I display a image only after it loads but the rest of the page shows normally? On each page I have something like this <html class"page-name"> and the css is as follows html.page-name { background: url(images/page-name.jpg) no-repeat center center fixed; background-size: cover; }

I tried to do the javascript as $(window).load(function(){ $('html').fadeIn(1500); });

but this obviously doesn't work because the hole page is blank until the image is loaded. I want the background to be black until the image is loaded and than replace it to the black background. I also tried $(window).load(function(){ $('html').addClass('page-title'); }); where page-title class has transition effect but also doesn't work.

How do I achieve this, having a black background and replace it with an image after it fully loads ?

Thank you.

user2513485
  • 25
  • 1
  • 4
  • 1
    I've just copied your question title to Google and voila: http://stackoverflow.com/questions/7331261/show-all-images-only-after-their-complete-load Tailor it for your needs. – keaukraine Aug 08 '13 at 07:18

2 Answers2

4

Load image dynamically and then on its onload add it to the background

$(document).ready(function(){
    var img = new Image();
    img.onload = function(){
      // image  has been loaded
      $("html.page-name").css("background-image","url('"+image_url+"')");
    };
    img.src = image_url;
})    
Anupam
  • 7,966
  • 3
  • 41
  • 63
  • if we have multiple images to load like this how will we get **image_url** for each when loaded? – Minhaz Feb 01 '14 at 21:38
  • @mebjas I did not get your question properly. For multiple images you have to write separate onload handlers – Anupam Feb 03 '14 at 06:37
1

jQuery:

// Wait for page load
$(function() {
  // apply background image class to body (fade over 500 milliseconds)
  $('body').addClass('page-title', 500);
});

CSS:

.page-title {
   background-image: url('/path_to/image.jpg');
 }
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Bradley Flood
  • 10,233
  • 3
  • 46
  • 43