Skip to content

Instantly share code, notes, and snippets.

@pierrehenri220
Created December 6, 2016 01:25
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pierrehenri220/58690c83d8c8d5c9308a35a240b34d69 to your computer and use it in GitHub Desktop.
Save pierrehenri220/58690c83d8c8d5c9308a35a240b34d69 to your computer and use it in GitHub Desktop.
Update html head tags with Barba.js
Barba.Dispatcher.on('newPageReady', function(currentStatus, oldStatus, container, newPageRawHTML) {
// html head parser borrowed from 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']"
].join(',');
$( 'head' ).find( headTags ).remove(); // Remove current head tags
$newPageHead.find( headTags ).appendTo( 'head' ); // Append new tags to the head
});
@pierrehenri220
Copy link
Author

pierrehenri220 commented Dec 6, 2016

@sadeghbarati
Copy link

sadeghbarati commented Oct 9, 2018

hey ! thanks for sharing ❤️
how about vanilla js without jQuery methods ? 👍

@pierrehenri220
Copy link
Author

pierrehenri220 commented Oct 12, 2018

Hi @Riiccardo I still haven't tested yet but on an other coding sns (the japanese network Qiita) the user @min30327 has ported it like this:

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();

Source: https://qiita.com/grenouille220/items/e94dac423da0c461daa7
Hope this help and thanks to Okudaさん

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment