LoginSignup
6
7

More than 5 years have passed since last update.

pjaxまとめとメモ

Last updated at Posted at 2018-06-26

pjaxまとめとメモ

pjaxは2種類ある

pjaxにはdefunktfalsandtruの2種類ある事に注意。
それぞれ、導入方法、使い方も違う。

■defunkt
https://github.com/defunkt/jquery-pjax

■falsandtru
https://github.com/falsandtru/pjax-api

*IE未対応

詳しい違いはこちらから
https://github.com/falsandtru/pjax-api/tree/master

■defunktの場合

まずはjquery.pjax.jsをインストール

git clone https://github.com/defunkt/jquery-pjax.git

クローンしたファイル内にあるjquery.pjax.jsをhtmlファイルに読み込む

<script src="/js/jquery.pjax.js"></script>
<script src="/js/config.js"></script>

基本の使い方

config.js
  $.pjax({
    container : '#pjax-container', 内容を書き換える要素指定
    fragment : '#pjax-container' 取得したい要素指定
  });

fragmentで取得したい要素を明示的に設定をしないと、
動的に書き換えられたmetaが、body内に追加されてしまう。

jsを再読み込み

ページ遷移後はjsが動かないので、
インラインでscriptを書くか、jsを再読み込みさせる。

$(document).on('pjax:complete' ,function(){
    $.getScript('script', function(){
        読み込み後の処理
    })
});

meta

タイトルは動的に変更され、
その他ogp周りなどのmetaは各ページごとに設定しておけばOK

loding処理

簡単なloding処理はイベントを使って追加出来る。
詳しいイベント一覧はこちら
https://github.com/defunkt/jquery-pjax#events

ページ遷移アニメーション

ページ遷移アニメーションを追加する場合、$.pjaxでの書き換え処理のタイミングを制御する必要がある。
簡単な処理はanimateのcallbackでも良いが、複雑なアニメーション、タイミングを制御したいのでpromiseを使って制御する。
詳しいイベント一覧はこちら
https://github.com/defunkt/jquery-pjax#events

ブラウザバック

ブラウザの戻る、進むボタンを使うにはリンクを絶対パスにする

ページ遷移後の処理

ページ遷移時animationの処理をclassの付け替えで制御している場合、
遷移後に処理を削除しておくこと。
詳しいイベント一覧はこちら
https://github.com/defunkt/jquery-pjax#events

■falsandtruの場合

まずはmodulesのインストール

npm install pjax-api spica

pjax-api、spicaそれぞれのdistに入っているjsをhtmlファイルに読み込む

<script src="/js/pjax-api.js"></script>
<script src="/js/config.js"></script>

基本の使い方

config.js
var Pjax = require('pjax-api').Pjax;
new Pjax({
  areas: [
    // try to use the first query.
    '#header, #primary',
    // fallback, retrying with the second query.
    '#container',
    // fallback.
    'body'
  ]
});

jsを再読み込み

ページ遷移後はjsが動かないので、
インラインでscriptを書くか、jsを再読み込みさせる。

$(document).on('pjax:ready' ,function(){
    $.getScript('script', function(){
        読み込み後の処理
    })
});

meta

metaも自動的に取得してくれる。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7