JavaScript Image Loader (V1.8.2013)
Creating an Image Loader Using JavaScript
Many modern web apps use custom scripts that load all assets (images, files, external scripts... etc.) prior to calling the main application function. The purpose of a loader script is to prevent errors caused by a program that tries to manipulate assets before they are fulled downloaded. Unfortunately there aren't many tutorials available for this subject so I've created this post to show you how to create a simple loader script. This example is specifically designed for images but the basic principles will apply to the other asset types.Before looking at any detailed code lets break down the process step by step.
- A visitor will enter our website/web app address into a browser.
- The page will begin to load.
- Once the page has finished loading it will call a function called 'loadImages()' that initiates the image loading process.
- loadImages() will cycle through a list of image links one at a time.
- Each image link will be allocated to a new image object and the new object will have a function assigned to each of the following events: onload, onerror and onabort.
- As each image loads or fails it will call the function 'calculateStatus()'. This function counts all images that have loaded/failed and calculates the width of a div element based on the percentage of completeness. Once the function detects that 100% of the images have loaded and/or failed it will call the next function that the website/web app requires, in our case it's just an alert function that tells us the images have loaded.
Now that we have discussed the basic process we can begin writing the loader script.
1. The first thing we need to do is create a new HTML5 document as shown below:
<!DOCTYPE html>
<html>
<head>
<title>Image Loader Script</title>
<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
</head>
<body>
</body>
</html>
2. Create the loader status bar by nesting two div elements within the body element. The outside div will be the red bar and the inner div will be the green "status" bar. Set the outer div id to "LoadBarBackground" and set the inner div id to "LoadBar".
<div id="LoadBarBackground">
<div id="LoadBar"></div>
</div>
3. Next we need to create the CSS styles in the head element. (At this point if we load the page in a browser we should see a thin red loading bar.)
<style>
#LoadBarBackground{
width:300px;
height:10px;
padding:0px;
margin:0px;
background-color:red;
border-radius:10px;
}
#LoadBar{
width:0px;
height:10px;
padding:0px;
margin:0px;
background-color:green;
border-radius:10px;
}
</style>
4. Now we are ready to insert the script tag into the head element and set the global variables. Please refer to the comments in the code for a more detailed explanation.
<script>
//Set global variables
//Create global img array
var img = new Array();
//Create global variable that will count the total number of images loaded
var ImageLoadCount=0;
//Create global array of image URLs to load
//Replace all image URLs with your own and add more as necessary
var ImageLinkArray=[
'http://img.timeinc.net/time/photoessays/2008/trees/franklin_trees_01.jpg',
'http://www.dailygalaxy.com/photos/uncategorized/2007/10/17/trees_2.jpg',
'http://www.redorbit.com/media/uploads/2012/12/TreesDeclining_120712-617x416.jpg',
'http://www.thisiscolossal.com/wp-content/uploads/2012/01/tree-2.jpg',
'http://www.onearth.org/files/onearth/article_images/08spr_trees_01_h_feature.jpg',
'http://www.ces.ncsu.edu/fletcher/programs/xmas/images/fawn-trees-bryandavis.jpg',
'http://natureblognetwork.com/blog/wp-content/uploads/2010/01/042907_trees_1.jpg'
];
</script>
//Set global variables
//Create global img array
var img = new Array();
//Create global variable that will count the total number of images loaded
var ImageLoadCount=0;
//Create global array of image URLs to load
//Replace all image URLs with your own and add more as necessary
var ImageLinkArray=[
'http://img.timeinc.net/time/photoessays/2008/trees/franklin_trees_01.jpg',
'http://www.dailygalaxy.com/photos/uncategorized/2007/10/17/trees_2.jpg',
'http://www.redorbit.com/media/uploads/2012/12/TreesDeclining_120712-617x416.jpg',
'http://www.thisiscolossal.com/wp-content/uploads/2012/01/tree-2.jpg',
'http://www.onearth.org/files/onearth/article_images/08spr_trees_01_h_feature.jpg',
'http://www.ces.ncsu.edu/fletcher/programs/xmas/images/fawn-trees-bryandavis.jpg',
'http://natureblognetwork.com/blog/wp-content/uploads/2010/01/042907_trees_1.jpg'
];
</script>
5. The next step is to create the imageLoader() function and place it directly after the ImageLinkArray within the script tag. Again, please refer to the comments in the code for a more detailed explanation.
function loadImages(){
//Loop through each image link and create an image reference to each
for(i=0;i<ImageLinkArray.length;i++){
//Create a new image object
img[i]=new Image();
//Set the currently selected link as the image source for the new object
if(ImageLinkArray[i] == '' || ImageLinkArray[i] == 'undefined'){
//Set source to fake url if array index was left blank to force img[i].onerror event
img[i].src='eRroR666.jpg';
}else{
img[i].src=ImageLinkArray[i];
}
//Attach function to onload event for each image
img[i].onload=function(){
//Add one to the total image count now that the image has loaded
calculateStatus();
}
//Attach function to onerror event for each image
img[i].onerror=function(){
//Add one to the total image count now that we know the image can't be loaded
calculateStatus();
alert('Image could not load.');
}
//Attach function to onabort event for each image
img[i].onabort=function(){
//Add one to the total image count now that we know the image was aborted
calculateStatus();
alert('Image load was aborted.');
}
}
}
//Loop through each image link and create an image reference to each
for(i=0;i<ImageLinkArray.length;i++){
//Create a new image object
img[i]=new Image();
//Set the currently selected link as the image source for the new object
if(ImageLinkArray[i] == '' || ImageLinkArray[i] == 'undefined'){
//Set source to fake url if array index was left blank to force img[i].onerror event
img[i].src='eRroR666.jpg';
}else{
img[i].src=ImageLinkArray[i];
}
//Attach function to onload event for each image
img[i].onload=function(){
//Add one to the total image count now that the image has loaded
calculateStatus();
}
//Attach function to onerror event for each image
img[i].onerror=function(){
//Add one to the total image count now that we know the image can't be loaded
calculateStatus();
alert('Image could not load.');
}
//Attach function to onabort event for each image
img[i].onabort=function(){
//Add one to the total image count now that we know the image was aborted
calculateStatus();
alert('Image load was aborted.');
}
}
}
6. Create the final function that calculates the percentage of completeness and adjusts the "LoadBar" div accordingly. This function will also call the next function in the application or in our case, an alert message.
function calculateStatus(){
//Add one to the total image count now that this image has loaded
ImageLoadCount++;
//Get the current width of the LoadBarBackground div
var LBBWidth = document.getElementById('LoadBarBackground').offsetWidth;
//Adjust the loader bar according to how many images have loaded so far
document.getElementById('LoadBar').style.width=((LBBWidth/ImageLinkArray.length)*(ImageLoadCount)) + "px";
//Check to see if all images have load
if(ImageLoadCount == ImageLinkArray.length){//If true, all images have been loaded
//Insert your next function call in place of this alert message
setTimeout(function(){alert("All images have loaded!");},3);
//Timer is used to ensure JavaScript DOM manipulation completes before next function call
}
//Update the total number images loaded in the global variable
return ImageLoadCount;
}
//Add one to the total image count now that this image has loaded
ImageLoadCount++;
//Get the current width of the LoadBarBackground div
var LBBWidth = document.getElementById('LoadBarBackground').offsetWidth;
//Adjust the loader bar according to how many images have loaded so far
document.getElementById('LoadBar').style.width=((LBBWidth/ImageLinkArray.length)*(ImageLoadCount)) + "px";
//Check to see if all images have load
if(ImageLoadCount == ImageLinkArray.length){//If true, all images have been loaded
//Insert your next function call in place of this alert message
setTimeout(function(){alert("All images have loaded!");},3);
//Timer is used to ensure JavaScript DOM manipulation completes before next function call
}
//Update the total number images loaded in the global variable
return ImageLoadCount;
}
7. Lastly we need to modify the opening body tag by assigning the loadImages() function to the onload event. This will trigger the image loader functions once the page has finished loading.
<body onload="loadImages()">
8. Save the html file and load it in a browser. You should see the green bar gradually fill in the red bar from left to right as the images load. Once the loading has completed you will get an alert message saying "All images have loaded!".
Congratulations, you have created your first image loader script! I hope you enjoyed this tutorial and I look forward to all the comments/suggestions! For all source code, demos and reference material please use the links below.
Resources
References
- DOM image object - W3Schools
- Image onload event - W3Schools
- Image onerror event - W3Schools
- Image onabort event - W3Schools
- Image src property - W3Schools
- JavaScript array object brief tutorial - W3Schools
- JavaScript array object detailed tutorial - Ilya Kantor
- JavaScript array reference - W3Schools
Comments
Post a Comment