Home Notes Web development jQuery, preloaders, and event delegation

jQuery, preloaders, and event delegation E-mail
Sunday, 29 March 2009 00:37

I set out this morning to create a pre-loader for my domain home, Pranshuarya.com.  Since I"m already using jQuery on the site and I feel comfortable with it, it only seemed natural to try to do it using jQuery.  I searched around for a while but nothing satisfactory was to be found.  Eventually I came across a script called Max's AJAX website preloader.  This pre-loader uses standard JavaScript to retrieve PHP and HTML content from a secondary file which it appends to the <body> tag of the index.html file where the pre-load animated GIF is being displayed.

It wasn't too much work to convert and compact the code using jQuery.  For my particular case the code went from:

// Get the HTTP Object
    function getHTTPObject(){
       if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
       else if (window.XMLHttpRequest) return new XMLHttpRequest();
       else {
          alert("Your browser does not support AJAX.");
          return null;
       }
    }  
 
    // Change the value of the outputText field
    function setOutput(){
       if(httpObject.readyState == 4){
          document.getElementById('myBody').innerHTML = httpObject.responseText;
       }
    }

// Implement business logic
    function loadSite(){
       httpObject = getHTTPObject();
       if (httpObject != null) {
          httpObject.open("GET", "content.php", true);
          httpObject.send(null);
          httpObject.onreadystatechange = setOutput;
       }
    }
     
    var httpObject = null;

to the following:
function loadSite(){
     jQuery.get("content.php", function(data) {
      jQuery('#loader').hide();
      jQuery('body').prepend(data);
      jQuery(jQuery.unblockUI);

After that it came down to adding the loadSite() function to the jQuery(document).ready() function along with BlockUI:
jQuery(document).ready(function() {
     jQuery.blockUI({
      message: '<img src="images/ajax-loader.gif" />',
      css: {
       width: '100px',
       backgroundColor: '#000',
       border: '0',
       top: '40%',
       left: '45%'
       }
     });
     loadSite();
    });

One tricky problem was the fact that the elements that events were to be bound to weren't created yet, since they would appear in the document after the content.php file was loaded.  To overcome that I used the Live query plugin for jQuery for easy event delegation:

jQuery('#switcher_wrapper > div').livequery('click', function() {

and that was all it took to add a simple pre-loader image (courtesy of Ajaxload.info, by the way), to a website.