AJAX - The Complete Reference

(avery) #1

Chapter 2: Pre-Ajax JavaScript Communications Techniques 41


PART I


linkedStyle.href = url;
/* find the head to insert properly */
var head = document.getElementsByTagName("head");
if (head)
head[0].appendChild(linkedStyle);

You can also create a special dummy tag that data in the returned style sheet will be
bound to.

/* We need to set a dummy div to assign the new style to */
var dummyDiv = document.createElement("div");
dummyDiv.id = "divforajax";
dummyDiv.style.display = "none";
document.body.appendChild(dummyDiv);

Once the request is sent, a timer is set to wake up every so often and check to see if the
style sheet has been returned and bound data to the dummy tag. If not, it goes back to sleep
for a bit more time and tries again later.

setTimeout("readResponse(1);", 50);
function readResponse(tries)
{
var resp = getElementStyle("divforajax", "backgroundImage", "background-image");
if (resp == "none" && tries < 10)
{
tries++ ; /* try again a bit later */
setTimeout("readResponse(" + tries + ");", 50);
return ;
}

Note that in the preceding code, we are simulating the callback ideas from previous
examples as well as the network timeout mechanism. Given that such options aren’t more
directly supported by the object, the use of a style sheet as a communication mechanism is
awkward. Add to this the ugly fact that the response data is commonly encoded as a
background-image URL, which then forks a bogus request shown in this network trace.
Free download pdf