Home arrow JavaScript arrow Page 5 - Preloading Images with the DOM: A Functional Image-Preloading Application
JAVASCRIPT

Preloading Images with the DOM: A Functional Image-Preloading Application


Here we are again. Welcome to the last part of the series “Preloading images with the DOM”. By utilizing a hands-on example, this series demonstrates how you can use a JavaScript http requesting script for preloading images in the background, based on the handy capabilities of AJAX and the DOM for fetching and processing files, without having to deal with traditional page reloads.

Author Info:
By: Alejandro Gervasio
Rating: 4 stars4 stars4 stars4 stars4 stars / 15
November 09, 2005
TABLE OF CONTENTS:
  1. · Preloading Images with the DOM: A Functional Image-Preloading Application
  2. · Refreshing code: A quick look at the existing script functions
  3. · Building image containers: defining the “createImageContainer()” function
  4. · Displaying enlarged images: coding the “displayImage()” function
  5. · Gluing the pieces: turning the application into a functional AJAX-based preloader

print this article
SEARCH DEVARTICLES

Preloading Images with the DOM: A Functional Image-Preloading Application - Gluing the pieces: turning the application into a functional AJAX-based preloader
(Page 5 of 5 )

Since the script takes care of generating thumbnail images after the web document has been loaded, the only additions that I’ll introduce into the original source code will be an “onload” event handler tied to the “window” object, for building in the thumbnails, as well as the required global variables used within the application. Given that, here’s the complete source code for the image-preloading script:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>AJAX-BASED IMAGE PRELOADER</title>
<script type="text/javascript">
// initialize XMLHttpRequest object
var xmlobj=null;
var loaded=false;
var pics=new Array();
// send http request
function sendRequest(elemid,file){
    // check for existing requests
    if(xmlobj!=null&&xmlobj.readyState!=0&&xmlobj.readyState!=4){
        xmlobj.abort();
    }
    try{
        // instantiate object for Mozilla, Nestcape, etc.
        xmlobj=new XMLHttpRequest();
    }
    catch(e){
        try{
            // instantiate object for Internet Explorer
            xmlobj=new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch(e){
            // Ajax is not supported by the browser
            xmlobj=null;
            return false;
        }
    }
    // assign state handler
    xmlobj.onreadystatechange=function(){
        stateChecker(elemid);
    }
    // open socket connection
    xmlobj.open('GET',file,true);
    // send request
    xmlobj.send(null);
}
// check request status
function stateChecker(elemid){
    // if request is completed
    if(xmlobj.readyState==4){
        // if status == 200 display text file
        if(xmlobj.status==200){
            // preload images
            preloadImages();
 // display image
 displayImage(elemid);
 loaded=true;
        }
        else{
            alert('Failed to get response :'+ xmlobj.statusText);
        }
    }
}
// preload images
function preloadImages(){
    // get image collection
    var imgcol=xmlobj.responseXML.getElementsByTagName('image');
    for(var i=0;i<imgcol.length;i++){
        // preload images
        pics[i]=new Image();
        pics[i].src=imgcol[i].firstChild.nodeValue+'.jpg';
    }
}
function createImageContainer(){
    // create image container
    var cdiv=document.createElement('div');
    cdiv.setAttribute('id','container');
    var img=document.createElement('img');
    img.setAttribute('width','400');
    img.setAttribute('height','277');
    img.setAttribute('id','largepic');
    // create 'close' paragraph
    var p=document.createElement('p');
    p.appendChild(document.createTextNode('Close window[-]'));
    cdiv.appendChild(p);
    cdiv.appendChild(img);
    p.onclick=function(){
        this.parentNode.parentNode.removeChild(this.parentNode);
    }
    document.getElementsByTagName('body')[0].appendChild(cdiv);
}
// create thumnails
function createThumbnails(numpics){
    for(var i=0;i<numpics;i++){
        var cdiv=document.createElement('div');
        cdiv.className='thumbnail';
        var a=document.createElement('a');
        a.setAttribute('href','#');
        a.setAttribute('id',i);
        // create thumbnails
        var img=document.createElement('img');
        img.setAttribute('width','120');
        img.setAttribute('height','77');
        img.setAttribute('border','0');
        img.setAttribute('src','thumbnail'+(i+1)+'.jpg');
        img.setAttribute('alt','click to enlarge');
        a.appendChild(img);
        cdiv.appendChild(a);
        document.getElementsByTagName('body')[0].appendChild
(cdiv);
        // assign 'onclick' event handler to <a> elements
        a.onclick=function(){
 // preload all images when the first image is clicked
 // or display the proper image
 (!loaded)?sendRequest(this.id,'images.xml'):displayImage
(this.id);        
        }
    }
}
// display image
function displayImage(elemid){
    var cdiv=document.getElementById('container');
    if(!cdiv){createImageContainer()};
    var newpic=pics[elemid];
    var oldpic=document.getElementById('largepic');
    if(!oldpic){return};
    oldpic.setAttribute('src',newpic.src);
}
// create thumbnails when page is loaded
window.onload=function(){
    // check if browser is DOM compatible
    if(document.getElementById&&document.
getElementsByTagName&&document.createElement){
        // create thumbnails
        createThumbnails(4);
    }
}
</script>
<style type="text/css">
p {
    font: bold 11px Verdana, Arial, Helvetica, sans-serif;
    color: #000;
}
div#container {
    position: absolute;
    top: 15px;
    left: 142px;
    background: #fc0;
    padding: 3px;
    border: 1px solid #000;
}
.thumbnail {
    width: 120px;
    background: #fc0;
    padding: 3px;
    border: 1px solid #000;
}
</style>
</head>
<body>
</body>
</html>

As you can see, the above listing is only the first half of the script, since the thumbnails, together with the larger images, haven’t been included. For this reason, and hopefully for making it easier to test the application, you can download here the ZIP file containing all the script files, along with the corresponding sample images.

To wrap up

Sad but true, that’s about it. Over this last part of the series, I’ve written the remaining functions that comprise the complete JavaScript image preloader, in addition to setting up a functional example. With reference to the growing support for AJAX on most of today’s browsers, we’ll see in the near future different implementations of this technology within a wide variety of Web applications. How deeply it will impact on the development of them is something that only time will tell. In the meantime, take the fast road and start using its powerful capabilities. You won’t be disappointed.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials