Use AJAX to Modularize (with Required Reading)

Purpose: The purpose of this exercise is to learn how to modularize HTML without server-side scripting. In the next section, we will use server-side scripting.

Required Textbook Reading: Please take time to read about the importance of modularizing code in general in Full-Stack Web Development Chapter 12, first section ("Code Organization and Modularity").

Setting Up the Need to Modularize

If you have not done so already, unzip the sample webpage from Exercise 0.2 into your document root. You may notice that all three have the same <nav> contents. The trouble with this is that if you want to change the nav, you need to change it in all three files. This is not only annoying, but is also likely to lead to inconsistency and errors as the project gets bigger. Please create common nav code as follows:

Client-Side Include

Create nav.html and copy in these lines:

The question then becomes, how do we include this HTML file in our three HTML files? Unfortunately, HTML was not designed to modularize this way. In this exercise, we will explore how this can be done with client-side javascript.

A Little History and Required Reading

Before 1999, the only way to insert custom HTML into a webpage was to reload the entire page and run a back-end script. In the late 1990s, Javascript began becoming universal in web browsers, and in 1999, the XMLHTTPRequest function was introduced, which allowed a webpage to send a request to a server, receive a response, and then do other actions like modifying the DOM. This process was later called AJAX (Asynchronous Javascript and XML). It was now possible, among other things, to modularize HTML from the client-side.

XMLHTTPRequest had its drawbacks, however, enough that we will not bother teaching it in this class, although you are welcome to try it out and learn it. In addition to requiring a few lines of setup, it required passing a callback function to tell the browser what to do when the response was received. This was not terrible until you needed to run multiple AJAX calls in a series. Then you would have to set up a series of callback functions like dominos and have each function process the response and make yet another AJAX call. Programmers found this so inconvenient that the term "callback hell" became a popular way to describe the process of setting up AJAX callback functions in series.

Several libraries were developed to ease the pains associated with XMLHTTPRequest, but in 2015, the introduction of the built-in "fetch" function and "promise" object into standard javascript quickly became the most popular way to deal with the issue. Please read more about fetch and promises (required reading). In 2017, the "async" and "await" keywords were added, making fetch and promise code even more simple and readable, and this approach has also become popular. Please read more about async and await (required reading).

Practice Fetch on the Console

Now that we've talked history, let's try it out. Assuming the sample webpage is still in your document root with the nav.html you created earlier, open up on your browser. Open up the Developer Tools console to enter the following javascript commands (re-type, don't copy) and see what happens, then feel free to mess around until you get the feel for how fetch and promises and await work:

Practice Fetch

Enter each command in console, one at a time (hover or click for explanation):

fetch("nav.html");
x = fetch("nav.html");
await x;
y = await x;
z = y.text();
await z;
result = await z;
result2 = await (
    await fetch("nav.html")
).text();

Write a Function to Include HTML

Please add the following function to your sample webpage from Exercise 0.2 to enable it to do a client-side include and try to understand each line. Re-type, don't copy.

Client-Side Include

Create index.js and add these lines:

Now add to index.html, about.html, and contact.html:

<script src="index.js"></script>

and make the nav element blank, as follows:

<nav></nav>

CORS Problems if You Load from File

You will notice, if you haven't tried it already, that this AJAX include works when you run it on , but it does not work when you open the HTML as a file from your computer without running it through localhost. That is because of a security block setting that prohibits Cross-Origin Resource Sharing (CORS), and localhost and file are considered two different origins. CORS policies are designed to prevent hacking, or at least to make it more difficult. Please experience this CORS problem as follows:

Experience CORS Problems

Run index.html as a file. Either:
• Double click on index.html in the folder, or
• Use "open" menu in your browser, or
• Enter "file://<path-to-index.html>" in the URL bar.

The include should not work. To see why, go to the Developer Tools console, and you should see a CORS policy error.

Other Problems that May Arise

Some browsers will try to run Javascript without loading the DOM fully, even when the Javascript is on the bottom as directed. If that happens, encapsulate your code in the following:

document.addEventListener("DOMContentLoaded", () => { ... Your Code ... });

Don't Delete Your Code Yet

The next exercise uses it.