Preloading Images with the DOM: The Introductory Process
If you have a website that displays a lot of images (particularly large images), your visitors with slow Internet connections may find themselves drumming their fingers as they wait for these images to load. Fortunately, there are a number of solutions to this problem. This article shows you how to develop a reusable JavaScript image preloading application, with help from the DOM and AJAX.
Preloading Images with the DOM: The Introductory Process - Requesting data from the server: fetching images through an XML file (Page 4 of 5 )
Since requesting files through XMLHttpRequest objects is a topic that I explained in some of my previous articles, I definitely won’t spend a long time explaining how this process is performed. Instead, I’ll briefly show the definition for the “sendRequest()” function, to give you a pretty clear idea of how images will be fetched from the server. Here is the function’s source code:
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); }
As you may have guessed, I’ll use this handy function to read the contents of the XML file containing the names of the images that will be preloaded. Its incoming arguments are the ID of the <a> element that was clicked on (in short, the thumbnail accessed by the visitor), as well as the file to be fetched. For this specific example, I’ll define a basic “images.xml” file, which looks like this:
Studying the above file, it becomes clear that all the <image> nodes are containers for image names. I’ve purposely coded the file that way, because of the extreme ease provided by AJAX for fetching XML files –- and specifically node values -- by utilizing the “XMLResponse” property of XMLHttpRequest objects. You can also see that the sequence image1, image2…image N isn’t mandatory at all. It’s possible to specify different image names, as long as they meet the rules for well-formed XML files.
Having defined the XML file, which stores image names, along with the function responsible for fetching it, we can move on to writing the next function of the application, “preloadImages()”, which not surprisingly does the work “behind the scenes” for preloading all the large images.