0 Comments

When I want to load a html fragment I prefer the contents of the container div in the page and the HTML fragment to have the same ID, like:

 

Master page

<!DOCTYPE html>
<html>
<head>
    <title>Master page</title>
</head>
<body>
    <!--Placeholder container. -->
    <div id="page"></div>
</body>
</html>

Page (html fragment)

<!DOCTYPE html>
<html>
<head>
    <title>Page (html fragment)</title>
</head>
<body>
    <!-- Page (html fragment to load). -->
    <div id="page"></div>
</body>
</html>

 

Then the following code can be used to replace the contents of the "placeholder" div, by the contents of the ”html fragment" div:

 

Code

// Loads a html fragment.
// It replaces the content of the given DOM element, with the html fragment contents.
// It expects both the current page and the html fragment to contain the same "id" as the given id.
//
// Parameters:
// [id] example ["#page"].
// [url] example ["Features/Login/LoginView.html"].
function loadHtmlFragment (id, url)
{
    // Use jQuery "ajax" instead of jQuery "load", because "load" will get the whole div, 
    // when used with selector "#page" and not the contents.
    // You can get only the contents with "load", by using "url #page > *", 
    // but that will only get the child elements of the div, 
    // stripping out any direct child text.
    $.ajax({
        url: url,
        type: 'GET',
        dataType: "html",
        success: function (data)
        {
            // Strip out any javascript by using "parseHtml".
            // Only use the contents of the html fragment by using "html()".
            var dom = $("<div>").append($.parseHTML(data)).find(id).html();

            // Adjust UI.
            $(id).html(dom);
        }
    });
};

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.