Lightbox and Ajax to display smoothly images

In the previous section, we have seen how to create a simple lightbox to show pictures. You have noted that the images are loaded slowly when the box appear, a disagreeable effect that we can remove by using Ajax. With just a function and without framework.

The Ajax code

No change in the CSS descriptors or JavaScript code to display box is necessary. We just add two extra functions to give Ajax features to the lightbox.

Loading an image with Ajax:

function preloading(i, url)
{
  var xhr=createXHR();   
  xhr.onreadystatechange=function()
  { 
     if(xhr.readyState == 4)
     {
       i.src = url;
     } 
  }; 
  xhr.open("GET", url , true);
  xhr.send(null); 
} 

The call of this function triggers asynchrone commands that are executed while the page is displayed.

The preloading function creates an instance of the XMLHttpRequest object (see code in resources below), and executes a GET command for loading a file. Nothing is sent by the send method, it suffices that the file is loaded into memory: we just want to have the image in memory...

Loading images in full size:

function loadAll()
{
  preloading(new Image(), "images/acores.gif");
  preloading(new Image(), "images/prison.gif");
  preloading(new Image(), "images/shark.jpg");
}

window.onload=loadAll;

The previous function is called for each image in original size and this is placed, that is an option, in a function called itself at loading of the page.

The images will be available in memory when you click on the thumbnails and can be displayed instantly!

Scrolling

With this version of the lightbox, the scrolling of the page has been taken into account.

To do so, we have to solve of lot of compatibility issues between browsers, but finally, we have achieved a code that works for all major recent browsers.

Under Gecko and Webkit renderers, we do use the "fixed" value for the position property. Under IE we have to process differently. See how in the JavaScript code of the demo.

The demonstration

All the files are included in the archive.

Download

© 2008-2014 Xul.fr