Preload Large Size Images Using jQuery - Preload.js

File Size: 78.3 KB
Views Total: 7266
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Preload Large Size Images Using jQuery - Preload.js

Preload.js is an ultra-light jQuery plugin that displays a loading spinner to preload large size images before loading them into the DOM.

How to use it:

1. Include the latest version of jQuery preload.js after loading jQuery library.

<script src="//code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="jquery.preload-1.2.0.js"></script>

2. Prepare the images you want to preload.

<img src="1.jpg" class="toLoad loadedContent">
<img src="2.jpg" class="toLoad loadedContent">
<img src="3.jpg" class="toLoad loadedContent">

3. Create the html for the image preloader.

<div class="loadingContent loadingCentre">
  <img src="preloader.gif">
  <div id="loadingBar"></div>
  <div id="loadingText">Loading 3 large files..</div>
</div>

4. Hide the images when preloading.

.toLoad { display: none; }

5. The sample CSS for the preloader.

.loadingCentre {
  position: absolute;
  height: 130px;
  width: 130px;
  left: 50%;
  top: 50%;
  margin-left: -65px;
  margin-top: -65px;
  background: #fafafa;
}

#loadingBar {
  width: 130px;
  height: 15px;
  border: 1px solid #ccc;
  border-radius: 20px;
}

.loadedContent { height: 800px; }

#loadingText {
  text-align: center;
  color: #AAA;
  font-size: 11px;
  font-family: arial;
}

6. Call the plugin as follows:

$(".toLoad").preload({

  // class of elements to show while loading
  loadingClass: 'loadingContent',  

  // Class of elements to show once loaded               
  loadedClass: 'loadedContent',                   
  
  // Optional function to call per element loaded (passing in index,totalCount)
  progressFunction: progress                      
   
  // Optional function to call once all are loaded 
  onComplete: complete     
                         
});

7. An example progress function:

function progress(x, total)
{       
  var p1 = parseInt(100/total*x);
  var p2 = p1 + 1;
  console.log(p1 + "," + p2);
  $("#loadingBar").css("background","linear-gradient(90deg, #3498db " + p1 + "%, #FFF " + p2 + "%)");       
}

8. An example completion function:

function complete()
{
  // Could put something in here to do after load (this replaces the default action)
  
  // This would do the same as the default function if it's wanted as well
  // $(".loadingContent").fadeOut(200, function(){$(".loadedContent").fadeIn(200);});            
}

This awesome jQuery plugin is developed by Tolansky. For more Advanced Usages, please check the demo page or visit the official website.