By now, nearly everyone who works in web development has heard of the term Ajax, which is simply a term to describe client-server communication achieved without reloading the current page. Most articles on Ajax have focused on using XMLHttp as the means to achieving such communication, but Ajax techniques aren't limited to just XMLHttpRequest. There are several other methods to achieve what AJAX can give to the end-user.
Dynamic Script Loading
The first alternate Ajax technique is dynamic script loading. The concept is simple: create a new element and assign a JavaScript file to its src attribute to load JavaScript that isn't initially written into the page. The beginnings of this technique could be seen way back when Internet Explorer 4.0 and Netscape Navigator 4.0 ruled the web browser market. At that time, developers learned that they could use the document.write() method to write out a tag. The caveat was that this had to be done before the page was completely loaded. With the advent of the DOM, the concept could be taken to a completely new level.
The Technique
The basic technique behind dynamic script loading is easy, all you need to do is create a element using the DOM createElement() method and add it to the page:
var oScript = document.createElement("script");oScript.src = "/path/to/my.js";document.body.appendChild(oScript);
Downloading doesn't begin until the new element is actually added to the page, so it's important not to forget this step. (This is the opposite of dynamically creating an element, which automatically begins downloading once the src attribute is assigned.)
Once the download is complete, the browser interprets the JavaScript code contained within. Now the problem becomes a timing issue: how do you know when the code has finished being loaded and interpreted? Unlike the element, the element doesn't have an onload event handler, so you can't rely on the browser to tell you when the script is complete. Instead, you'll need to have a callback function that is the executed at the very end of the source file.
Example 1
Here's a simple example to illustrate dynamic script loading. The page in this example contains a single button which, when clicked, loads a string ("Hello world!") from an external JavaScript file. This string is passed to a callback function (named callback()), which displays it in an alert. The HTML for this page is as follows:
Example 2
// -1) {
sUrl += "&";
} else {
sUrl += "?";
}
sUrl += encodeURIComponent(sName) + "=" + encodeURIComponent(oParams[sName]);
}
var oScript = document.createElement("script");
oScript.src = sUrl;
document.body.appendChild(oScript);
}
function messageFromServer(sText) {
alert("Loaded from file: " + sText);
}
function getInfo() {
var oParams = {
"name": document.getElementById("txtInput").value, "callback": "messageFromServer"
};
makeRequest("example2js.php", oParams);
}
//]]>
The JavaScript file example1.js contains a single line:
callback("Hello world!");
When the button is clicked, the makeRequest() function is called, initiating the dynamic script loading. Since the newly loaded script is in context of the page, it can access and call the callback() function, which can do use the returned value as it pleases. This example works in any DOM-compliant browsers (Internet Explorer 5.0+, Safari, Firefox, and Opera 7.0.
More Complex Communication
Sometimes you'll want to load a static JavaScript file from the server, as in the previous example, but sometimes you'll want to return data based on some sort of information. This introduces a level of complexity to dynamic script loading beyond the previous example.
First, you need a way to pass data to the server. This can be accomplished by attaching query string arguments to the JavaScript file URL. Of course, JavaScript files can't access query string information about themselves, so you'll need to use some sort of server-side logic to handle the request and output the correct JavaScript. Here's a function to help with the process:
function makeRequest(sUrl, oParams)
{
for (sName in oParams) {
if (sUrl.indexOf("?") > -1) {
sUrl += "&"; } else { sUrl += "?";
}
sUrl += encodeURIComponent(sName) + "=" + encodeURIComponent(oParams[sName]); }
var oScript = document.createElement("script"); oScript.src = sUrl; document.body.appendChild(oScript);
}
This function expects to be passed a URL for a JavaScript file and an object containing query string arguments. The query string is constructed inside of the function by iterating over the properties of this object. Then, the familiar dynamic script loading technique is used. This function can be called as follows:
var oParams = { "param1": "value1", "param2": "value2"};
makeRequest("/path/to/myjs.php", oParams)
Next, you need a way to assign the callback function to be used. It's quite possible that you'll want to access the same information on different pages and in different ways. Forcing each page to have a callback function named "callback" isn't very good architectural design. Instead, it would be better to tell the JavaScript file the name of the callback function to use so that it can be dynamically inserted. The name of the function can be passed as another parameter for the query string:
var oParams = { "param1": "value1", "param2": "value2", "callback": "myCallbackFunc"};
makeRequest("/path/to/myjs.php", oParams);
The file creating the JavaScript then has to take the name of the callback function and output it into the code, as below:
var sMessage = "Hello world!";
(sMessage);
The first part of this file sets the content type to text/javascript so that the browser recognizes it as JavaScript (though many browsers don't check the content type of files loaded using ) Next, a JavaScript variable called sMessage is defined as a string, "Hello world!". The last line outputs the name of the callback function that was passed through the query string, followed by parentheses enclosing sMessage, effectively making it a function call. If all works as planned, the last line becomes:
myCallbackFunc(sMessage);
Example 2
This example builds upon the previous one, but this time, you're going to send some additional information to the server and tell it which callback function to call. First, take a look at the PHP file that will be outputting the JavaScript:
var sMessage = "Hello, ";var sName = "
";
(sMessage + sName);
The JavaScript that will be output defines two variables, sMessage and sName; the former is filled with "Hello, ", the latter is assigned the value of the name parameter in the query string. Then, the name of the callback function is out, passing in the concatenation of sMessage and sName (combining server-side data with data passed from the client).
On the client side, the web page contains a textbox and a button:
html>
Example 2
// -1) {
sUrl += "&";
} else {
sUrl += "?";
}
sUrl += encodeURIComponent(sName) + "=" + encodeURIComponent(oParams[sName]);
}
var oScript = document.createElement("script");
oScript.src = sUrl;
document.body.appendChild(oScript);
}
function messageFromServer(sText) {
alert("Loaded from file: " + sText);
}
function getInfo() {
var oParams = {
"name": document.getElementById("txtInput").value, "callback": "messageFromServer"
};
makeRequest("example2js.php", oParams);
} //]]>
When the button is clicked, the getInfo() method is called, which loads an object with a name parameter (taken from the textbox) and a callback parameter. Then, the makeRequest() function is called, passing in these values. After the script has been loaded, the messageFromServer() function will be called, popping up a message displaying what was received from the server
Drawbacks
Though dynamic script loading is a quick and easy way to establish client-server communication, it does have some drawbacks. For one, there is no feedback once the communication is initiated. If, for example, the file you are accessing doesn't exist, there is no way for you to receive a 404 error from the server. Your site or application may sit, waiting, because the callback function was never called.
Also, you can't send a POST request using this technique, only a GET, which limits the amount of data that you can send. This could also be a security issue: make sure you don't send confidential information such as passwords using dynamic script loading, as this information can easily be picked up from the query string.
- Related Articles
- Related Q&A




How to Communicate With Other Electronic Devices on Your PC
By: Colon Bolden | 27/12/2009One of the things that makes computers so useful is the fact that they can communicate with other electronic devices. Via cables and telephone lines, your computer can talk to printers, fax machines and to other computers.
Pass4side 70-642 Exam Training materials
By: Adela1987 | 26/12/2009Pass4side 70-642 Practice Testing Software provides you an easy online solution to your Microsoft 70-642 Exam Preparation. With Pass4side 70-642 Practice Testing Software is tested on all Windows Platforms and contains the more recent Microsoft 70-642 Exam Objectives. You can use Pass4side 70-642 Practice Test on any PC with most versions of Windows and take the tests in two modes. One is Practice Mode and the other is learning mode for Microsoft 70-642 Certification Exam. You can check your ans
Pass4side Apple 9L0-509 exam Training
By: Adela1987 | 26/12/2009The Question and Answers are in PDF format that makes it easy for a student to study on any system. The 9L0-509 Dump Exams provide you with a 100 success guarantee. Each resource available from Actual Tests Cram has been hand crafted by our team of practicing IT Professionals. It is certain that your Pass4side Download 9L0-509, Q and A, and brain dumps are the highest quality, and customized to make the learning experience the best choice you can make in preparing for your Certification.
Pass4side 70-290 exam Braindumps
By: Adela1987 | 26/12/2009My suggestion is the best use of Pass4side, the money unless you are relatively well-off time.Many people think that long experience in the use of questions is not, Pass4side provides Microsoft 70-290 exam study materials,such as Microsoft 70-290 Braindumps, 70-290 Study Guides,70-290 exam Questions with Answers, 70-290 Training materials, 70-290 free demo and so on.
Pass4side 312-50 Study Guide
By: Adela1987 | 26/12/2009So you can get the exams from various resources but the logical and the precise explanation to your study guide questions is only here. 312-50 Study Guide page all the necessary 312-50 exam guide can be found. And it not only includes free 312-50 but it also contains 312-50 study guide and practice exams.
Pass4side 000-001 practice tests
By: Adela1987 | 26/12/2009Pass4side 000-001 Practice Questions are designed with questions, coupled with precise, logical and verified answer. Pass4side.com’s 000-001 practice exam provides you with an examination experience like no other. To take a more authentic exam, you would have to take the exam itself, in an exam center!
Pass4side 220-601 training tools
By: Adela1987 | 26/12/2009The CompTIA 220-601 Study Guide will take you from weak to geek in our 100% guaranteed solution for getting your head wrapped around the 220-601 exam content and theories. The 220-601 guide is the perfect prelude to using the 220-601 exam simulator. Designed to work together for the ultimate learning and comprehending experience – the 220-601 study guide is training done right!
Pass4side N10-004 study guide
By: Adela1987 | 26/12/2009Many IT specialists were not able to obtain the N10-004 certificate from the first attempt, which was the result of poor preparation for the examination, using preparatory N10-004 study guide of poor quality. Our N10-004 practice exams and study questions are composed by current and active Information Technology experts, who use their experience in preparing you for your future in IT area.
Silent Love Story
By: smrithi | 05/02/2008 | RelationshipsThis is a silent love story of how two hearts depart from each other and at last, their love towards each other helps them to live with each other forever
Alternative to Ajax
By: smrithi | 02/01/2008 | Information TechnologyThough AJAX evolved in the year 2005, its roots were from the already existing technologies and there was an alternative to AJAX technology in the olden but had some drawbacks