jQuery(document).ready(function(){ 在 Fadein 之前不等待背景图像先加载

jQuery(document).ready(function(){ isn't waiting for Background Image to load first before Fadein

我在使用 jQuery(document).ready(function(){ 时遇到问题 - 我的问题是当我清除缓存时它没有等待背景图像先加载然后淡入。所以发生的事情是在包装器淡入之前有一个延迟,然后图像在加载时明显缩小屏幕。

我正在 Wordpress 上使用 Headway Themes 进行构建。

这让我发疯:)

CSS:

@-webkit-keyframes fade-in {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}

.background-image {
  background: url('http://www.aliceandowl.com/wp-content/uploads/2015/03/Purity-London-Homepage-Banner.jpg') no-repeat center center fixed;

  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;

  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  opacity: 0;

  -webkit-animation-name: fade-in;
  -webkit-animation-duration: 1s;
  -webkit-animation-timing-function: ease-in;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-delay: 2s;
  -webkit-animation-fill-mode: forwards;
}

.background-image.visible {
  opacity: 1;
}

jQuery:

  jQuery(document).load(function() {
  jQuery('.background-image').on('webkitAnimationEnd', function(e) {
    jQuery(this).addClass('visible');
  });
});

我从以下位置定制了这个:http://codepen.io/graygilmore/pen/hxpEt

任何解决方案都不胜感激!

谢谢, 丹妮尔

我刚刚让网站上线(它正在建设中哈)- 你会在加载时看到背景图片: http://www.aliceandowl.com 谢谢大家!

到目前为止,所有给出的答案都在做同样的事情,问题仍然是淡入不等待背景图像先加载。

$(document).ready 不等待资源加载。它只是确保在 DOM 加载后调用回调 .

资源使用$(window).load,只有加载js/css/images等外部资源时才会触发回调

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

尝试用这个代替 $(document).ready():

$(window).on('load', function() {
    // Code here
});

您需要使用:.load();

这会等到所有图像、闪存...加载:$(document).load(function(){});

然而,这从不等待您的图像加载,它只会等待基本 HTML 加载: $(document).ready(function(){});

编辑: 尝试用你所有的 jQuery(document).load(function() { ...:

替换它
var image = 'http://graygilmore.com/images/bk-body.jpg',
        img = $('<img />');

img.bind('load', function() {
     $('.background-image').addClass('visible');
});

img.attr('src', image);
$('.background-image').css('background-image', 'url(' + image + ')');

注释掉

//background: url('http://graygilmore.com/images/bk-body.jpg') no-repeat center center fixed;

已解决!我休息了一下,然后又回到了它,这通常会有所帮助,我遇到了以下现在可以完美运行的东西,谢谢你们所有的帮助!

CSS:

.background-image {
  background: url('http://www.aliceandowl.com/wp-content/uploads/2015/03/Purity-London-Homepage-Banner.jpg') no-repeat center center fixed; 

    display: none;

    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0; 
}

jQuery:

jQuery(window).load(function(){
    jQuery('<img/>').attr('src', 'http://www.aliceandowl.com/wp-content/uploads/2015/03/Purity-London-Homepage-Banner.jpg').load(function() {  
      jQuery('.background-image').fadeIn(2000);
    });
  });

现在我要喝最大杯的酒 ;)