My website utilizes XMLHttpRequests to fetch specific parts of webpages upon a user clicking a link.
Below is the relevant code snippet:
function requestPage(url, push) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
main.innerHTML = xhr.responseText;
attachLinkClickHandlers(main); // `main` = container element
if (push)
window.history.pushState(url, title, url);
}
};
xhr.open('GET', url);
xhr.setRequestHeader('Content-Only', 1);
xhr.send();
}
window.addEventListener('popstate', function (e) {
var page = e.state;
requestPage(page, false);
});
window.history.replaceState(location.href, document.title, location.href);
attachLinkClickHandlers(document);
When a link is clicked:
requestPage(link.href, true);
Here are examples of server responses:
Response from normal request:
<!doctype html>
<html>
<head>
...stuff...
</head>
<body>
<main>
<h1>Content</h1>
<p>Content Content</p>
</main>
</body>
</html>
Response when Content-Only
header is set:
<h1>Content</h1>
<p>Content Content</p>
Everything seems to be working correctly, except when I click on an external link and then try to navigate back using the browser's back button. At that point, only the content without the usual HTML, head, or body tags is displayed as per XHR response, meaning CSS and JavaScript are also missing.
I'm looking for suggestions on how to ensure the browser loads the complete page in such scenarios.