Jul 14, 2014

Spinner and how to preload background images

If you want to use background image for your web but it took too long to load, what can you do ?
You probably want to show a preloader (or spinner) while your background image is being loaded, right ?

If so, here are the steps (demo: http://codepen.io/anon/pen/FHCJw)

1. To display the spinner / preloaded: 
HTML:
<!DOCTYPE html>
 
<html>
<head>
 <meta charset="utf-8" />
 <title></title>
</head>
<body>
 <div id="preloader_wrap">
  <div id="spinner_wrap">
   <div class="spinner">
    <div class="rect1"></div> 
    <div class="rect2"></div> 
    <div class="rect3"></div> 
    <div class="rect4"></div> 
    <div class="rect5"></div>
   </div>
  </div>
 </div>
 <div id="content">Your content here</div>
</body>
</html>

CSS:
#preloader_wrap {
 positionfixed;
 top0;
 left0;
 right0;
 bottom0;
 background-color#fff;
 z-index999;
}
 
#spinner_wrap {
 width200px;
 height200px;
 positionabsolute;
 left50%;
 top50%;
 background-repeatno-repeat;
 background-positioncenter;
 margin-100px 0 0 -100px;
}
 
.spinner {
 margin100px auto;
 width50px;
 height30px;
 text-aligncenter;
 font-size10px;
}
 
 .spinner > div {
  background-color#2980b9 /*dark blue*/;
  height100%;
  width6px;
  displayinline-block;
  -webkit-animationstretchdelay 1.2s infinite ease-in-out;
  animationstretchdelay 1.2s infinite ease-in-out;
 }
 
 .spinner .rect2 {
  -webkit-animation-delay-1.1s;
  animation-delay-1.1s;
 }
 
 .spinner .rect3 {
  -webkit-animation-delay-1.0s;
  animation-delay-1.0s;
 }
 
 .spinner .rect4 {
  -webkit-animation-delay-0.9s;
  animation-delay-0.9s;
 }
 
 .spinner .rect5 {
  -webkit-animation-delay-0.8s;
  animation-delay-0.8s;
 }
 
@-webkit-keyframes stretchdelay {
 0%40%100% {
  -webkit-transformscaleY(0.4);
 }
 
 20% {
  -webkit-transformscaleY(1.0);
 }
}
 
@keyframes stretchdelay {
 0%40%100% {
  transformscaleY(0.4);
  -webkit-transformscaleY(0.4);
 }
 
 20% {
  transformscaleY(1.0);
  -webkit-transformscaleY(1.0);
 }
}
 2. To hide the spinner when your image is loaded:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
 <script type="text/javascript">
  var jpgFile = 'http://farm4.staticflickr.com/3812/11264786296_891530550e_o.jpg'//or your own picture
 
  $("<img/>").attr('src', jpgFile).load(function() {
    $("#preloader_wrap").hide(); 
   $("body").css("background""url('" + jpgFile + "') no-repeat center center fixed"); 
   $("#content").show();
  });
 </script>

That's it ! You'll have a nice preloader and a nice background

No comments:

Post a Comment