Change Language


Follow Navioo On Twitter

AJAX Speed Up the Web

< < < Speed Web delivery with HTTP compression Part1


AJAX Speed Up the Web -DEMO

In the AJAX tutorial below we will demonstrate how a web page can be loaded 10 time faster using ajax.

This is the HTML page . It contains a simple HTML table,couple css rules and a link to a JavaScript:


CREATE SIMPLE HTML TEMPLATE

testSpeedFrames.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="boosterhtml.js" ></script> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My Page</title>
</head>

<body>

 

<table width="100%" border="0" cellspacing="3" cellpadding="3"> <tr> <td> <table width="100%" border="0" cellspacing="3" cellpadding="3"> <tr> <td>header -logo place.. </td> <td>header- menu .. </td> </tr> </table> </td> </tr> <tr> <td>
<table width="100%" border="0" cellspacing="3" cellpadding="3"> <tr> <td width="20%">left side </td> <td>
//Center part <div id="dynamicContent" > <br/><br/><br/><br/><br/><br/><br/><br/> center side(Content) <br/><br/><br/><br/><br/><br/><br/><br/> </div> </td> <td width="20%">Right Side </td> </tr> </table>
</td> </tr> <tr> <td> <table width="100%" border="0" cellspacing="3" cellpadding="3">
<tr>
<td>footer </td>
</tr>
</table> </td> </tr>
</table>
<!-- Start dynamic template We hide by default this part using style="display:none" for our layer <div id="tempate_dynamic" .. //-->

<div id="tempate_dynamic" style="display:none" class="ex1">
<fieldset class="ex1"> <legend ><b><font color="#009900"> <!--This is where we placed the reserved word type_add //--> type_add </font></b>Ad&nbsp;#Published on:&nbsp; <!--This is where we placed the reserved word date_add //--> date_add </legend> <table width="100%"> <tr> <td colspan="3" height="3" align="right"><b> category_name </b> </td> </tr>
<tr> <td align="" valign="top" width="86"> <img <!--This is where we placed the reserved word images //--> src="images.jpg" border="0" width="53"> <br/> <br style="line-height: 5px;" /> </td> <td></td> <td valign="top" width="90%"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody> <tr> <td colspan="2" height="9"></td> </tr> <tr> <td colspan="2" align="left"><span class="ml5"><b> <!--This is where we placed the reserved word title //--> title </b></span></td> </tr> <tr> <td colspan="2" height="1"></td> </tr> <tr> <td colspan="2" align="left" style="overflow: hidden;padding-left: 5px; padding-bottom:3px;" bgcolor="#eaeceb" > <!--This is where we placed the reserved word description //--> description .. </td> </tr> <tr> <td colspan="2" height="8"></td> </tr> <tr> <td align="left"><span class="tx6">Price:&nbsp; </span><span class="tx7"> <!--This is where we placed the reserved word priceadd //--> priceadd $</span> <b>Distance:&nbsp;</b> <!--This is where we placed the reserved word _distance_ //--> _distance_ </td> <td width="" align="right"> <img src="button_details.gif" border="0" height="18" width="63" onclick="alert('detail Add-'+id_items);"> <img src="button_add_to_cart.gif" border="0" height="18" width="63" onclick="alert('Send Add-'+id_items);"> </td> </tr> </tbody> </table> </td> </tr> </table> </fieldset> </div> <!-- End dynamic template //-->

</body>
</html>


The HTML Template for repeated/dynamic zone

We use this big template (aprox 2KB) for repeated part of our page.It's to make more suggestive our tutorial:

<div id="tempate_dynamic" style="display:none" class="ex1">
<fieldset class="ex1"> <legend ><b><font color="#009900"> <!--This is where we placed the reserved word type_add //--> type_add </font></b>Ad&nbsp;#Published on:&nbsp; <!--This is where we placed the reserved word date_add //--> date_add </legend> <table width="100%"> <tr> <td colspan="3" height="3" align="right"><b> category_name </b> </td> </tr>
<tr> <td align="" valign="top" width="86"> <img <!--This is where we placed the reserved word images //--> src="images.jpg" border="0" width="53"> <br/> <br style="line-height: 5px;" /> </td> <td></td> <td valign="top" width="90%"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody> <tr> <td colspan="2" height="9"></td> </tr> <tr> <td colspan="2" align="left"><span class="ml5"><b> <!--This is where we placed the reserved word title //--> title </b></span></td> </tr> <tr> <td colspan="2" height="1"></td> </tr> <tr> <td colspan="2" align="left" style="overflow: hidden;padding-left: 5px; padding-bottom:3px;" bgcolor="#eaeceb" > <!--This is where we placed the reserved word description //--> description .. </td> </tr> <tr> <td colspan="2" height="8"></td> </tr> <tr> <td align="left"><span class="tx6">Price:&nbsp;</span><span class="tx7"> <!--This is where we placed the reserved word priceadd //--> priceadd $</span> <b>Distance:&nbsp;</b> <!--This is where we placed the reserved word _distance_ //--> _distance_ </td> <td width="" align="right"> <img src="button_details.gif" border="0" height="18" width="63" onclick="alert('detail Add-'+id_items);"> <img src="button_add_to_cart.gif" border="0" height="18" width="63" onclick="alert('Send Add-'+id_items);"> </td> </tr> </tbody> </table> </td> </tr> </table> </fieldset> </div>

Example Explained - The HTML Form

As you can see, the HTML page above(tutorial_speed_up.html) contains a simple HTML template with an layer called "dynamicContent" where we bind our content dynamic generate in boosterhtml.js With function parseResult(str).

The form works like this:

  1. An event(onclick) is triggered when the user click one of the Categorys links
  2. When the event is triggered, a function called GetResult() is executed.
  3. Below in the template (tutorial_speed_up.html)is a <div> called "tempate_dynamic". This is used as a placeholder for the dynamic part (HTML code) used by of the parseResult() function to generate the dynamic content in page.

The JavaScript

The JavaScript code is stored in "boosterhtml.js" and linked to the HTML document:

	  var xmlHttp
var arr_items=new Array();
function GetResult(id)
{

xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="dataserver.php"
url=url+"?id="+id
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
parseResult(xmlHttp.responseText)
}
}

function parseResult(str)
{
eval(str);
var message_no_result="No result";
//Get Dynamic Template
var final_string=' ';
alert(arr_items.length+ " Rows");
for (i=0;i<(arr_items.length-1);i++){
var my_template=document.getElementById("tempate_dynamic").innerHTML;
my_template=my_template.replace(/id_items/g,arr_items[i][0]);
my_template=my_template.replace(/title/g,arr_items[i][1]);
my_template=my_template.replace(/description/g,arr_items[i][2].substring(0,70));
my_template=my_template.replace(/priceadd/g,arr_items[i][3]);
my_template=my_template.replace(/images/g,arr_items[i][4]);
my_template=my_template.replace(/date_add/g,arr_items[i][5]);
my_template=my_template.replace(/email/g,arr_items[i][6]);
final_string=final_string+my_template;

}
if(arr_items.length==0){
document.getElementById("dynamicContent").innerHTML=message_no_result;
}else{
document.getElementById("dynamicContent").innerHTML=final_string;
}
}

Example Explained

The GetResult() Function

This function executes every time a character is entered in the input field.

If there is some input in the text field (str.length > 0) the function executes the following:

  1. Defines the url (filename) to send to the server
  2. Adds a parameter (id) to the url with the id of the Category
  3. Adds a random number to prevent the server from using a cached file
  4. Calls on the GetXmlHttpObject function to create an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered
  5. Opens the XMLHTTP object with the given url.
  6. Sends an HTTP request to the server

If the input field is empty, the function simply clears the content of the ViewResult placeholder.

The stateChanged() Function

This function executes every time the state of the XMLHTTP object changes.When the state changes to 4 (or to "complete"), the content of the ViewResult placeholder is filled with the response text. 

The GetXmlHttpObject() Function

AJAX applications can only run in web browsers with complete XML support.The code above called a function called GetXmlHttpObject().The purpose of the function is to solve the problem of creating different XMLHTTP objects for different browsers.This is explained in the previous chapter.

The parseResult(str) Function

We have one parameters - str =xmlHttp.responseText;.Whit javascript eval() this string become our javascript array already declared in top of "boosterhtml.js" var arr_items=new Array();After With one simple loop on start replacing our reserved word in my_template :

var my_template=document.getElementById("tempate_dynamic").innerHTML;

At the end we bind final_string in <div id="dynamicContent" >....

document.getElementById("dynamicContent").innerHTML=final_string;

That's all!


OPTIONAL FOR THE Server-Side The PHP Page

The server page called by the JavaScript code is a simple PHP file called "dataserver.php".

The output of "dataserver.php" returned to the client is formated like a javascript bidimensional array of corresponding items(in our case we named arr_items) :

arr_items=[
            ["2","Title2","Description ,Description  ","34","img2","2007-08-07 18:56:30",""],
            ["4","title4","Description4 ,Description ","34","img2","2007-08-07 18:56:30",""],
            ["5","title5","Description5 ,Description","34","img1","2007-08-07 18:56:30",""],
            ["7","title7","Description7 ,Description ","34","img2","2007-08-07 18:56:30",""], 
            ["8","title8","Description8 ,Description ,","34","img2","2007-08-07 18:56:30",""],
            ["10","title10","Description10 ,Description  ","24","img1","2007-08-07 18:56:30",""], 
            ["11","title11","Description11 ,Description ","36","img2","2007-08-07 18:56:30",""]
          ];

<?
$host = "localhost";
// database username $user = "user_name"; // database password $pass = "your_pass";

// database name $database = "ajax";
mysql_connect("$host","$user","$pass"); mysql_select_db("$database");

$mysql= "SELECT * FROM items WHERE subcategorie =".$_GET["id"]; $r = mysql_query($mysql) ;


$result .= " arr_items=[\r\n";
while ($row = mysql_fetch_array($r)) { $result .= " ["; $result .='"'.addslashes($row["id"]).'"'. ","; $result .='"'.addslashes($row["title"] ). '"'.","; $result .='"'.addslashes($row["description"] ). '"'.","; $result .='"'.addslashes($row["prix"] ). '"'.","; $result .='"'.addslashes($row["img1"] ). '"'.","; $result .='"'.addslashes($row["created_date"] ). '"'.","; $result .='"'.addslashes($row["email"] ). '"'.""; $result .= "],\r\n"; }
// delete comma $result = substr( $result, 0, -3 ); $result .= "\r\n];";
echo $result;

If there is any id sent from the JavaScript ( GetResult(id) ) the following happens:

  1. Find all items matching the category id sent from the JavaScript
  2. Include all resulted items in the response string ( formatted string like javascript array );
  3. The response is received in client and processed With javascript function (parseResult(str))
  4. If one or more matching names were found, set response to these names
  5. The response is received in client and processed With javascript function (parseResult(str))

Tests+CONCLUSION

With Firebug-Network Monitoring we start monitoring /comparing network activity
First test:10 rows
Classic Page-> tutorial_speed_up_ini10rows.html AJAX Category 1 in our case
Second test:60 rows
Classic Page-> tutorial_speed_up_ini60rows.html AJAX Category 2 in our case

LIVE WORKING website www.bizcaf.com where we are made this tests (Classified adds website )BETA VERSION


Ajax Javascript feed

↑ Grab this Headline Animator