JavaScript: Asynchronous Downloads
Page 4
Asynchronous Downloads
Introduction
This section demonstrates how to load an XML file in such a way that it appears asynchronous, with a call back function. The call back function activates when the file loads. While waiting for the file, code remains responsive. If the file doesn't load, then an error should display, however some errors might not execute the call back function.
In this example, tap the Next button on a game prototype. XML data should display in the game's multiple choice set of options. See JavaScript source code with the XMLHttpRequest Code feature. JavaScript downloads an XML file and displays the next question in this example. However for game play you might want to respond to correct answers and keep score.
Single Thread
Most online sources indicate that JavaScript isn't multithreaded. JavaScript runs on one thread in most browsers. However, as JavaScript advances quickly that might not be the case anymore.
If JavaScript remains single threaded
then the term, asynchronous, doesn't
truly apply to JavaScript.
However, perhaps time slices
apply to various JavaScript features, which
allow those features to appear asynchronous.
Time Slices
For example consider downloading a very large file
with XMLHttpRequest()
, as this example
demonstrates. Perhaps Web browsers
send the request then continue to respond to
user interaction on the Web page, until
the XMLHttpRequest()
response activates.
Therefore one thread calls XMLHttpRequest()
.
The same thread responds to user interaction,
while also processing the XMLHttpRequest()
, in
small alternating sections of time.
That thread is then interrupted when
the XMLHttpRequest()
response activates.
The XMLHttpRequest()
response stops
any other activity on the main thread.
Other File Types
This example loads an XML file, however consider asynchronous downloads for non XML files, especially large assets such as images or 3D models.
Load Asynchronous XML File
The following example demonstrates how to download a level in a non-partisan political game, about the US Constitution. Select the Next button to see the next question.
See the XMLHttpRequest Code on this page or within the JavaScript file async.js.
Style sheet rule sets, for the prototype game, are declared in file multi.css. Questions, answers and image source strings reside in the XML file qa.xml.
Tap Next Button.
XMLHttpRequest Code
You may also download JavaScript file, async.js.
// Path to XML file: const sXMLPath = "assets/qa.xml"; var xmlhttp = null; var xmlDoc = null; var xmlQuestions = null; // We'll just show // the second entry. // In a game, increment // iIndex per question: var iIndex = 1; // Question options: var hRb0, hRb1, hRb2 = null; // Question: var eQu = null; // Various errors etc. var eDebug = null; /** * Event listener for * body onload event. */ function loadQA(){ hRb0 = document.getElementById('hRb0'); hRb1 = document.getElementById('hRb1'); hRb2 = document.getElementById('hRb2'); eQu = document.getElementById('eQu'); } /** Asynchronous request * to load an XML file * @param fCallBack: Function to * execute in response to request. */ function loadXML(fCallBack){ let req = new XMLHttpRequest(); req.open('GET', sXMLPath); req.onload = function() { if (req.status == 200) { // Display XML to // Game page. fCallBack(req.responseXML); } else { fCallBack(null); } } req.send(); } function loadNext(){ loadXML(onFileLoad); } /** * Respond if file * loaded or not loaded. * * @param x: XML document * or null. */ function onFileLoad(x){ if(x == null){ // Display an error message // to the user. eDebug.innerHTML += "Error loading file." } else{ xmlDoc = x; } // Obtain array of questions: xmlQuestions=xmlDoc.getElementsByTagName("qu"); // Show a set of questions. viewQuestion(); } /** * Display XML data * to HTML elements * on the Web page. */ function viewQuestion(){ eQu.innerHTML = xmlQuestions[iIndex].getElementsByTagName("q")[0].childNodes[0].nodeValue; var rb = xmlQuestions[iIndex].getElementsByTagName("rb"); hRb0.innerHTML = rb[0].childNodes[0].nodeValue; hRb1.innerHTML = rb[1].childNodes[0].nodeValue; hRb2.innerHTML = rb[2].childNodes[0].nodeValue; }
Summary
This page demonstrates how to load an XML file in such a way that it appears asynchronous, with a call back function. The call back function activates when the file loads. While waiting for the file, code remains responsive. If the file doesn't load, then an error should display, however some errors might not execute the call back function.
Consider asynchronous downloads for other file types, especially large assets such as images or 3D models.
You may download, study or use the the JavaScript file, async.js, XML file qa.xml and style sheet multi.css.
Learn JavaScript
JavaScript's the foundation of Web developer and Website design skills. This free and unique JavaScript tutorial includes some new or seldom used, but useful features.