18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 15<br />

To load the file asynchronously, use the readyState property and the onreadystatechange event<br />

handler.<br />

The readyState property has five possible values:<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

0 — The DOM hasn’t been initialized with any information.<br />

1 — The DOM is loading data.<br />

2 — The DOM has completed loading the data.<br />

3 — The DOM may be used although some sections may not be available.<br />

4 — The DOM is completely loaded and ready to be used.<br />

Whenever the readyState property changes from one value to another, the readystatechange event<br />

is fired. If you use the onreadystatechange event handler, you are notified when the DOM has been<br />

fully loaded:<br />

oXmlDom.onreadystatechange = function () {<br />

if (oXmlDom.readyState == 4) {<br />

alert(“Done”);<br />

}<br />

};<br />

You must assign the onreadystatechange event handler before you call the load() method, as shown<br />

in the following:<br />

oXmlDom.onreadystatechange = function () {<br />

if (oXmlDom.readyState == 4) {<br />

alert(“Done”);<br />

}<br />

};<br />

oXmlDom.load(“test.xml”);<br />

Now when the file is completely loaded, you see the alert Done.<br />

You may note that the event handler code uses oXmlDom instead of the this keyword.<br />

This is a peculiarity of ActiveX objects in <strong>JavaScript</strong>: The this keyword doesn’t<br />

always work as expected. To avoid any problems, it’s best to use the full variable<br />

name in the event handler.<br />

448<br />

Whether you choose to load files synchronously or asynchronously, the load() method can be used<br />

with a partial, relative, or full path to the XML file, such as in the following:<br />

oXmlDom.load(“test.xml”);<br />

oXmlDom.load(“../test.xml”);<br />

oXmlDom.load(“http://www.mydomain.com/test.xml”);<br />

The partial and relative paths are always calculated from the page using the XML DOM object, just as a<br />

link or image would be.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!