Q:

How can I take common large chunks of oft-reused HTML source code?

A slew of pages I've written for one of my web projects share some 144 identical lines of code, reproduced in each file. If I update one of those lines, I have to go back through ALL of the pages that share the code and update for each page. Is there a straightforward way to include HTML from a separate file?
And for bonus points, since so many pages use this code, it would be nice not to have to reload it for each page. Is there an easy way to store it in the browser's cache or only load the "content" section of the pages while leaving the rest of the page static?
Fountains of Thanks for any wisdom on this.
Mike

A:

To include HTML from a separate file, use SSI (Server-Side Includes). This requires SSI support to be installed on the server, however.
You would write something like this in your files:
<!--#include file="included.html" -->
and that would include the file included.html when the page is accessed.
To load only the content of each page, use the XMLHTTPRequest object from JavaScript:
function LoadContent(url)
{
    if (typeof(XMLHttpRequest) == "undefined")
    {
        try
        {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
                // fallback for browsers without XMLHttpRequest
                window.location.href = "no-ajax.php?url="+escape(url);
                return;
            }
        }
    }
    else
    {
        xmlhttp = new XMLHttpRequest();
    }
    xmlhttp.open("GET", url, false); // this request will be synchronous (will pause the script)
    xmlhttp.send();
    if(xmlhttp.status > 399) // 1xx, 2xx and 3xx status codes are not errors
    {
        // put error handling here
    }
    document.getElementById("content").innerHTML = xmlhttp.responseText;
}

