18
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Barba.jsを使って、metaタグを動的に更新する方法

Last updated at Posted at 2016-12-06

newPageReadyのイベントで使用するようになります。例:

Barba.Dispatcher.on( 'newPageReady', function( currentStatus, oldStatus, container, newPageRawHTML ) {
    if ( Barba.HistoryManager.history.length === 1 ) {  // ファーストビュー
        return; // この時に更新は必要ありません
    }
    // jquery-pjaxから借りた
    var $newPageHead = $( '<head />' ).html(
        $.parseHTML(
            newPageRawHTML.match( /<head[^>]*>([\s\S.]*)<\/head>/i )[ 0 ],
            document,
            true
        )
    );
    var headTags = [ // 更新になってほうしいタグ
        "meta[name='keywords']",
        "meta[name='description']",
        "meta[property^='og']",
        "meta[name^='twitter']",
        "meta[itemprop]",
        "link[itemprop]",
        "link[rel='prev']",
        "link[rel='next']",
        "link[rel='canonical']",
        "link[rel='alternate']"
    ].join( ',' );
    $( 'head' ).find( headTags ).remove(); // タグを削除する
    $newPageHead.find( headTags ).appendTo( 'head' ); // タグを追加する
});
Barba.Pjax.start();

@min30327 がコメントで書いた通り
jQueryを使用ずにネイティーブJSも変更可能です:

Barba.Dispatcher.on( 'newPageReady', function( currentStatus, oldStatus, container, newPageRawHTML ) {
    if ( Barba.HistoryManager.history.length === 1 ) {
        return;
    }
    var head = document.head,
        newPageRawHead = newPageRawHTML.match( /<head[^>]*>([\s\S.]*)<\/head>/i )[ 0 ],
        newPageHead = document.createElement( 'head' );
    newPageHead.innerHTML = newPageRawHead;
    var headTags = [ 
        "meta[name='keywords']",
        "meta[name='description']",
        "meta[property^='og']",
        "meta[name^='twitter']",
        "meta[itemprop]",
        "link[itemprop]",
        "link[rel='prev']",
        "link[rel='next']",
        "link[rel='canonical']",
        "link[rel='alternate']"
    ].join( ',' );
    var oldHeadTags = head.querySelectorAll( headTags );
    for ( var i = 0; i < oldHeadTags.length; i++ ) {
        head.removeChild( oldHeadTags[ i ] );
    }
    var newHeadTags = newPageHead.querySelectorAll( headTags );
    for ( var i = 0; i < newHeadTags.length; i++ ) {
        head.appendChild( newHeadTags[ i ] );
    }
});
Barba.Pjax.start();
18
24
1

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
18
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?