萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

HTML5 History API 實現無刷新瀏覽器前進後退與 SPA 路由核心原理

核心對象:history 與 location

History 對象屬性

屬性說明
length歷史記錄條目數(當前標籤頁),隱私保護下不可見具體 URL
state當前歷史條目關聯的狀態對象,由 pushState/replaceState 設置
scrollRestoration'auto'|'manual' 控制歷史導航時是否自動恢復滾動位置

History 對象方法

// 導航(不改變 history.length)
history.back();        // 後退
history.forward();     // 前進
history.go(-2);        // 後退 2 步
history.go(0);         // 刷新頁面

// 狀態管理(改變 URL 不刷新)
history.pushState(stateObj, title, url);    // 新增歷史條目,length+1
history.replaceState(stateObj, title, url); // 替換當前條目,length 不變

// 參數說明:
// stateObj: 任意可序列化對象,popstate 事件中可讀取 event.state
// title: 當前被所有瀏覽器忽略,傳 '' 即可
// url: 同源 URL (相對/絕對路徑),跨域會拋錯

Location 對象常用屬性/方法

// 可讀寫屬性
location.href       // 完整 URL
location.protocol   // 'https:'
location.host       // 'example.com:8080'
location.hostname   // 'example.com'
location.port       // '8080'
location.pathname   // '/path/to/page'
location.search     // '?query=string'
location.hash       // '#anchor'
location.origin     // 'https://example.com:8080' (只讀)

// 方法
location.assign(url)   // 跳轉並記錄歷史 (length+1)
location.replace(url)  // 跳轉替換當前歷史 (length 不變)
location.reload()      // 刷新

// 無刷新改變 URL (僅 hash 部分)
location.hash = 'section2'; // 觸發 hashchange & popstate

關鍵事件:popstate 與 hashchange

事件觸發條件event.state備註
popstate用戶點擊前進/後退、history.go()、history.back()、location.hash 改變 (含 pushState 帶 hash)當前歷史條目 state 對象頁面加載不觸發;pushState/replaceState **不觸發**
hashchangelocation.hash 發生變化無老瀏覽器兼容方案核心
// 監聽歷史變化,執行路由邏輯
window.addEventListener('popstate', function(e) {
  var state = e.state; // { page: 'detail', id: 123 }
  if (state) {
    router.navigate(state.page, state); // 應用層路由處理
  }
});

// hashchange 兼容降級
window.addEventListener('hashchange', function() {
  var hash = location.hash.slice(1); // 去掉 #
  if (hash) router.navigate(hash);
});

SPA 路由實現核心邏輯

// 簡易 History 路由器
var router = {
  routes: {},
  
  // 註冊路由
  on: function(path, handler) {
    this.routes[path] = handler;
  },
  
  // 導航到路徑
  navigate: function(path, state) {
    // 1. 更新歷史
    history.pushState(state || {}, '', path);
    // 2. 執行處理器
    this._dispatch(path);
  },
  
  // 替換當前歷史 (登錄後重定向等)
  replace: function(path, state) {
    history.replaceState(state || {}, '', path);
    this._dispatch(path);
  },
  
  _dispatch: function(path) {
    var handler = this.routes[path] || this.routes['*']; // 404 fallback
    if (handler) handler(path);
  },
  
  // 初始化:監聽 popstate + 處理初始路徑
  init: function() {
    window.addEventListener('popstate', (e) => this._dispatch(location.pathname));
    this._dispatch(location.pathname); // 首次加載
  }
};

// 使用
router.init();
router.on('/', () => renderHome());
router.on('/article/:id', (path) => {
  var id = path.split('/')[2];
  renderArticle(id);
});
router.on('*', () => render404());

老舊瀏覽器降級方案 (IE9-)

  • 不支持 pushState/replaceState/popstate
  • 唯一可控無刷新修改 URL 的方式:修改 location.hash
  • 不支持 hashchange 事件 (IE7-),需 輪詢 檢測 location.hash 變化
// 兼容性路由核心 (簡化版 History.js 思想)
var HashRouter = (function() {
  var lastHash = location.hash;
  var listeners = [];
  
  function check() {
    var curr = location.hash;
    if (curr !== lastHash) {
      lastHash = curr;
      listeners.forEach(function(fn) { fn(curr); });
    }
  }
  
  // 輪詢 (IE7-)
  var interval = setInterval(check, 100);
  
  // 現代瀏覽器用事件
  if ('onhashchange' in window) {
    clearInterval(interval);
    window.addEventListener('hashchange', check);
  }
  
  return {
    navigate: function(hash) { location.hash = hash; },
    on: function(fn) { listeners.push(fn); },
    destroy: function() { 
      clearInterval(interval); 
      window.removeEventListener('hashchange', check); 
    }
  };
})();

觀察者模式優雅實現 URL 變化通知

// 被觀察者:URL 管理器
function UrlManager() {
  this.observers = [];
  this.currentHash = location.hash;
}

UrlManager.prototype = {
  addObserver: function(observer) { this.observers.push(observer); },
  removeObserver: function(observer) { 
    var i = this.observers.indexOf(observer); 
    if (i > -1) this.observers.splice(i, 1); 
  },
  notify: function() { 
    this.observers.forEach(function(o) { o.update(); }); 
  },
  setHash: function(hash) {
    location.hash = hash;
    this.notify(); // 主動通知,無需輪詢
  }
};

// 觀察者:頁面模塊
function ArticleViewer() {}
ArticleViewer.prototype.update = function() {
  var hash = location.hash;
  if (hash.startsWith('#article/')) {
    this.loadArticle(hash.slice(9));
  }
};

// 使用
var urlMgr = new UrlManager();
var viewer = new ArticleViewer();
urlMgr.addObserver(viewer);
urlMgr.setHash('#article/123'); // 觸發 viewer.update()

最佳實踐總結

  1. 優先使用 History API (pushState + popstate),URL 美觀、利於 SEO、無 # 干擾
  2. 服務端配合:所有路由請求返回同一個 index.html (或模板入口),由前端路由接管
  3. 滾動恢復:設置 history.scrollRestoration = 'manual' 手動控制,避免跳轉後頁面亂跳
  4. 狀態對象精簡:state 僅存必要數據 (如 {id: 123}),大對象存 sessionStorage
  5. 避免在 popstate 中異步請求阻塞 UI:預加載、骨架屏、Suspense
copyright © 萬盛學電腦網 all rights reserved