/* * 新闻静态页软导航:点击站内 /news/ 链接时,用 fetch 拉取目标页并仅替换 #news-app 区域, * 配合 history.pushState / popstate 实现无整页刷新跳转,CSS/JS 走浏览器缓存,避免每次从 OSS 重新下载整页。 */ (function () { var APP_ID = 'news-app'; function isInternal(href) { if (!href) return false; var a = document.createElement('a'); a.href = href; if (a.origin !== location.origin) return false; return a.pathname.indexOf('/news/') === 0; } function swap(url) { fetch(url, { credentials: 'omit' }) .then(function (r) { if (!r.ok) throw new Error('http ' + r.status); return r.text(); }) .then(function (html) { var doc = new DOMParser().parseFromString(html, 'text/html'); var incoming = doc.getElementById(APP_ID); var current = document.getElementById(APP_ID); if (!incoming || !current) { location.href = url; return; } current.innerHTML = incoming.innerHTML; var t = doc.querySelector('title'); if (t) document.title = t.textContent; ['canonical', 'alternate'].forEach(function (rel) { var neo = doc.querySelector('link[rel="' + rel + '"]'); var old = document.querySelector('link[rel="' + rel + '"]'); if (neo && old) old.outerHTML = neo.outerHTML; }); window.scrollTo(0, 0); }) .catch(function () { // 兜底:fetch 失败(如跨域/网络异常)则退回普通跳转 location.href = url; }); } document.addEventListener('click', function (e) { if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; var a = e.target.closest('a'); if (!a) return; var href = a.getAttribute('href'); if (!isInternal(href)) return; var target = new URL(href, location.href); if (target.pathname + target.search === location.pathname + location.search) return; e.preventDefault(); history.pushState({ url: href }, '', href); swap(href); }); window.addEventListener('popstate', function (e) { if (e.state && e.state.url) swap(e.state.url); }); })();