JavaScript
  Home arrow JavaScript arrow Page 5 - Preloading Images with the DOM: A Function...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Preloading Images with the DOM: A Functional Image-Preloading Application
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 10
    2005-11-09

    Table of Contents:
  • Preloading Images with the DOM: A Functional Image-Preloading Application
  • Refreshing code: A quick look at the existing script functions
  • Building image containers: defining the “createImageContainer()” function
  • Displaying enlarged images: coding the “displayImage()” function
  • Gluing the pieces: turning the application into a functional AJAX-based preloader

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

       · In the last tutorial of this series, the remaining JavaScript functions that...
     

    JAVASCRIPT ARTICLES

    - Building Dynamic Shadows with JavaScript and...
    - Active Client Pages: Chrys`s Approach
    - The Script Approach to Active Client Pages: ...
    - Principles of Active Client Pages: the Scrip...
    - Active Client Pages: the Script Approach
    - Building an RTF-capable Form with the Ext JS...
    - Creating a Multi-Tabbed Online Form with the...
    - jQuery Overview
    - Constructing a Multi-Column Online Form with...
    - Grouping Field Sets on Dynamic Web Forms wit...
    - Building Dynamic Web Forms with the Ext JS F...
    - More on JavaScript Array Objects
    - Methods of the DOM Location Object
    - The DOM Location Object Properties
    - Handling Remote Files with JavaScript Click ...







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT