非同期で別ページを読み込む

電脳備忘録

これまで行ったヲタクライブの履歴をaboutページに時系列で記載していたのですが、縦に長くなりすぎたので年ごとに分割することにしました。
クリックすると履歴記載したhtmlを所定の場所に読み込んで表示します。まぁこんなんでええやろ・・・。
このページの一番下に実装しています。

const asyncLinks = document.querySelectorAll('.link-button');
function loadPage(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status === 200) {
const content = document.getElementById('history-content');
content.innerHTML = xhr.response;
} else {
console.error('Error loading page.');
}
};
xhr.send();
}
asyncLinks.forEach(link => {
link.addEventListener('click', function(event) {
event.preventDefault();
loadPage(this.href);
});
});

広告

ブログの維持費に充てるでございます・・・。