Friday, 30 May 2014

Preload images with Javascript

It is useful to preload large or multiple images to avoid long waiting times. I have used the Javascript plugin called 'imagesLoaded' which can trigger an event when all images have been loaded. While the images are loading a preloaded gif can be displayed until the images have loaded. The preloader will be removed once all the images have been loaded. This will give the user feedback so they know content is loading.

Firstly, in HTML file I have added the class 'loading' to the body tag. This class will show the preloader gif when the images are loading and will be removed once the images have loaded. I have added the images to be preloaded inside a div with the class 'preload'. This div will be hidden until the images have loaded.

<!doctype html>
<html lang="en" class="no-js">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>Preload image Javasript</title>
   <link rel="stylesheet" href="css/style.css">
   <script src="js/vendor/modernizr-2.7.1.min.js"></script> 
</head>
<body class="loading">

   <div class="preload">
       <img src="img/img1.jpg">
       <img src="img/img2.jpg">
       <img src="img/img3.jpg">
       <img src="img/img4.jpg">
   </div>
    
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
   <script src="js/imagesloaded.js"></script>
   <script>
       //add javascript code here
   </script>

</body>
</html>

In the css file, the loading class displays the preloaded gif positioned at the centre of the page. The preload class uses the 'display none' to hide the images. Once the images have loaded the body opacity will be opaque.

body{
     opacity: 0;
}    

.loading {
    background: url('../images/loading.gif') no-repeat center center;
}

.preload {
    width: 1px;
    height: 1px;
    position: absolute;
    top: 0;
    left: 0;
    display: none;
}

.loaded, .no-js  {    
    opacity: 1;
    -webkit-transition: opacity 300ms ease-out;
    -moz-transition: opacity 300ms ease-out;
    transition: opacity 300ms ease-out;
}

Finally, in the HTML file I have added the following Javascript code using the imagesLoaded plugin. This code will remove the class 'loading' from the body an add the 'loaded' class.

$(function() {
 $('body').imagesLoaded(function() {
      $('body').removeClass('loading').addClass('loaded');
 });
});

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP