Revised solution for Jerome

by alano

HTML

<div id="main">
    <!--We will hide this when we load the target page-->
    <h1>Contents List</h1>
    <ul id="theList"></ul>
</div>

JavaScript

//IMPORTANT: this code will only execute if the target url's are exist on the domain where this page is being hosted 

var promises = [], urls = [
    { url: 'http://www.austudio.fr/jerome/files/idfile1.html' },
    { url: 'http://www.austudio.fr/jerome/files/idfile2.html' }];

function ALink(aUrl) {
    //force the "new" keyword at each instantiation
    if (typeof ALink != "function") return new ALink(aUrl);
    //initially, return an unresolved "promise" back to the caller
    var promise = $.Deferred();
    $.ajax({
        url: aUrl.url,
        complete: function (jqXHR) {
            aUrl.jqXHR = jqXHR;
            //resolve the promise regardless of AJAX status
            promise.resolve();
        }
    });
    return promise;
}

function buildList() {
    var $contents = $("ul#theList");
    //parse the text of each page to create the links
    $.each(urls, function (i, u) {
        if (u.jqXHR.statusText !== "OK") {
            //failed to fetch specified url, create dummy diagnostic link
            $contents.append("<li>" + unescape(u.url) + ": " + u.jqXHR.statusText + "</li>");
        } else {
            var $h1Elements = $("h1", u.jqXHR.responseText);
            if ($h1Elements.length == 0) {
                $contents.append("<li>" + unescape(u.url) + " : No H1 tags found within page</li>");
            } else {
                $h1Elements.each(function () {
                    var aLink = "<li><a href='" + u.url + "#" + $(this).attr("id") + "'>"
                    aLink += unescape(u.url) + " : " + $(this).text() + "</a></li>";
                    $contents.append(aLink);
                });
            }
        }
    });
}

//THE WHOLE PROCESS STARTS HERE, once the initial Contents page has loaded...
$(document).ready(function () {
    $.each(urls, function(i, u) {
        //load each page into memory and fetch a promise for each
        promises.push(new ALink(u));
    });
    //wait for all promises to complete then build the index
   ...