良いアプローチは、pushStateを使用することです。
これにより、最新のブラウザーでは、同じページ (つまり、同じ JavaScript 実行環境) にとどまりながら URL を変更できます。
アイデアは、アプリを古典的なマルチページ Web サイトとして作成pushState
し、popstate
イベントを使用して JavaScript ルーティングを処理することです。
これには大きな利点があります。
- 完全なウェブサイトには、ユーザーが直接アクセスできる一意の URL がまだあります
- したがって、検索エンジンによってインデックス可能です
- 古いブラウザのユーザーは、ページ全体を更新して通常どおりリンクをたどるだけなので、正常に劣化します
履歴の処理は多くの意味を持つ深いトピックであるため、それに関するドキュメントを読む必要があります (それを処理するヘルパー JavaScript フレームワークを使用している場合でも) が、基本は次のとおりです。
$( 'a' ).click( function( event ){
// check if pushState is supported
if ( window.history && window.history.pushState ){
var $link = $( this );
event.preventDefault();
// change url
history.pushState( {}, '', $link.attr( 'href' ) );
// call your page change handler, which typically
// request content, add it in page and show it
// with animation - you're responsible of implementing
// this `change_page` method
change_page( $link.attr( 'href' ) );
}
});
// triggered when user press the back button
// *and* on page load
$(window).on( 'popstate', function(){
// does the page change
change_page( window.location.href );
});