Created
December 6, 2016 01:25
-
-
Save pierrehenri220/58690c83d8c8d5c9308a35a240b34d69 to your computer and use it in GitHub Desktop.
Update html head tags with Barba.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); |
hey ! thanks for sharing ❤️
how about vanilla js without jQuery methods ? 👍
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
Original post: http://1.grenouille220.com/2016/12/barbajs-update-metas.html