CIS-2450 Lab #4: Inclusions with JavaScript

Reading: The MDN documentation on Promises provides some interesting background material. The documentation is more detailed than we need for this lab. The MDN documentation on fetch is, perhaps, more directly useful, but understanding something about Promises will help with understanding the fetch documentation.

Part 1: Basic Example

It is a common need to include the same content on every page on a website. Common footers, headers, and navigation controls are typical examples. There are various ways to achieve this depending on when the inclusions take place. If page fragments are combined at deployment time, various templating technologies can be used. If the server combines page fragments, technologies such as SSI, PHP, etc., can be used. In this lab we will combine page fragments in the front end as the page is being rendered by using JavaScript.

Begin by demonstrating the example shown in class.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
</head>
<body>
    <div id="header"></div> <!-- This is where the header will be inserted -->

    <p>This is the main content of the page.</p>

    <script>
        // JavaScript to load the header
        fetch('header.html')
            .then(response => response.text())
            .then(data => {
                document.getElementById('header').innerHTML = data;
            });
    </script>
</body>
</html>

If you access this page without making header.html, the page fails to render. Access the JavaScript console in your web browser using Ctrl+Shift+I to see more information.

Now create a file named header.html and observe that it works as expected.

To deal with the error case more gracefully, look at the first example on the fetch documentation page where the response is checked for an HTTP error code. Try throwing an error if the response is not a successful HTTP transfer, and then handle that error in the Promise's catch method at the end of your then calls. Note: The Promise does not consider a 404 response from the server as a failure. When you use fetch, the only "failure" is a problem with the client/server communication itself.

Part 2: PHP (OPTIONAL!)

If you are feeling adventurous, try setting up PHP on your system (notes for Windows users, notes for macOS users), and then using PHP to solve the same problem the JavaScript is solving in Part 1 above.

Submission

For this lab submit your main file(s) for Part 1 and, if you tried it, Part 2. You don't need to submit header.html.


Last Revised: 2024-09-27
© Copyright 2024 by Peter Chapin <peter.chapin@vermontstate.edu>