Jekyllサイトを開発するときに使用するスタジオ用の開始テンプレートを作成しようとしていますが、ページアニメーションの切り替えを行う必要があります。このための最良のアプローチは、AJAXを使用して各ページからさまざまなコンテンツをロードし、次にpushStateを使用してURLとブラウザの履歴を更新することです。pushStateとJekyllでAJAXを使用する
私は、AJAXの読み込みを行い、すべてのpushStateエントリを実行するコードを作り出しました。また、前後のボタンも履歴のために働いています。 私が問題を抱えているのは、ページのタイトルを更新することです。私はそれをajaxLoad関数に入れて、ユーザーがリンクをクリックしたときとブラウザの履歴に戻るボタンと進むボタンを使うときの両方で起こるようにしたい。しかし、私はこれを達成するためにどのようなコードを使うべきか正確には分かりません。
このようなタスクを達成しようとしたのは初めてのことですから、もう1つ質問してください。これは賢明な方法でコード化されていますか?あるいは、私はどのような方法にも違ったアプローチをするべきですか?
main.js
$(function() {
var changedPage = false,
/* ----- Do this when a page loads ----- */
init = function() {
/* ----- This is where I would run any page specific functions ----- */
console.log("Initializing scripts");
},
/* ----- Do this for ajax page loads ----- */
ajaxLoad = function(html) {
init();
/* ----- Here you could maybe add logic to set the HTML title to the new page title ----- */
/* ----- Used for popState event (back/forward browser buttons) ----- */
changedPage = true;
},
loadPage = function(url) {
$("#content").load(url + " #content", ajaxLoad);
console.log("Ajax Loaded");
};
/* ----- This runs on the first page load with no ajax ----- */
init();
$(window).on("popstate", function(e) {
if (changedPage) loadPage(location.href);
console.log("Popstate happened");
});
$(document).on('click', 'a', function() {
var url = $(this).attr("href"),
title = $(this).text();
if (url.indexOf(document.domain) > -1 || url.indexOf(':') === -1) {
history.pushState({
url: url,
title: title
}, title, url);
loadPage(url);
return false;
}
});
});
ジキルテンプレートので
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>{{ page.title }}</title>
<meta name="viewport" content="width=device-width">
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/main.css">
</head>
<body>
<div class="site">
<div class="header">
<h1 class="title"><a href="/">{{ site.name }}</a></h1>
<a class="extra" href="/">home</a>
</div>
<div id="content">
{{ content }}
</div>
<div class="footer">
<div class="contact">
<p>
Your Name is<br /> What You Are<br /> [email protected]
</p>
</div>
<div class="contact">
<p>
<a href="https://github.com/yourusername">github.com/yourusername</a><br />
<a href="https://twitter.com/yourusername">twitter.com/yourusername</a><br />
</p>
</div>
</div>
</div>
<script src="/js/jquery-3.2.0.min.js"></script>
<script src="/js/main.js"></script>
</body>
</html>
この現在のコード、Ajaxを使ってページのコンテンツをロードする機能は、ブラウザのpushStateとしていますすべて働いている。
Barba.jsは、すべてのAJAXのパフォーマンスを扱うの美しい仕事をしていませんし、持っている: