From fc48f00a349204e0ac3759ae5876bab492ba728d Mon Sep 17 00:00:00 2001 From: Jonas Braathen Date: Sun, 4 Aug 2019 21:21:06 +0200 Subject: [PATCH] Fix loading embedded content from Twitter and Instagram when navigating --- gatsby-browser.js | 31 +++++++++++++++++++++++++++++++ gatsby-ssr.js | 21 +++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 gatsby-browser.js create mode 100644 gatsby-ssr.js diff --git a/gatsby-browser.js b/gatsby-browser.js new file mode 100644 index 0000000..f2fa6b2 --- /dev/null +++ b/gatsby-browser.js @@ -0,0 +1,31 @@ +/* global twttr instgrm */ + +const loadTwitter = () => { + if ( + typeof twttr !== `undefined` && + twttr.widgets && + typeof twttr.widgets.load === `function` + ) { + twttr.widgets.load(document.getElementById('___gatsby')) + } +} + +const processInstagram = () => { + console.log('process') + if ( + typeof instgrm !== `undefined` && + instgrm.Embeds && + typeof instgrm.Embeds.process === `function` + ) { + console.log('yes') + instgrm.Embeds.process() + } +} + +const initScripts = () => { + loadTwitter() + processInstagram() +} + +exports.onInitialClientRender = initScripts +exports.onRouteUpdate = initScripts diff --git a/gatsby-ssr.js b/gatsby-ssr.js new file mode 100644 index 0000000..62377bf --- /dev/null +++ b/gatsby-ssr.js @@ -0,0 +1,21 @@ +const React = require('react') + +const SCRIPTS = { + Twitter: 'https://platform.twitter.com/widgets.js', + Instagram: 'https://www.instagram.com/embed.js', +} + +const createScriptTag = (key, scriptSrc) => { + return React.createElement( + 'script', + { src: scriptSrc, key: `gatsby-plugin-oembed-${key.toLowerCase()}` }, + null + ) +} + +exports.onRenderBody = ({ setPostBodyComponents }, options) => { + const scriptKeys = ['Twitter', 'Instagram'] + + const scripts = scriptKeys.map(key => createScriptTag(key, SCRIPTS[key])) + setPostBodyComponents(scripts) +}