birkir / gatsby-source-prismic-graphql

Gatsby source plugin for Prismic GraphQL
MIT License
137 stars 75 forks source link

[Solution] Prevent preview script from being downloaded if not needed #228

Open Bram-Zijp opened 4 years ago

Bram-Zijp commented 4 years ago

I thought id just drop this here as a solution for those who need and as inspiration for the plugin author. It basically injects a script that will check if it has the expected value's to load the preview script.

// inside gatsby-ssr.js
import React from 'react';

const injectPrismaScriptHtml = `
(function(){
  var isPreviewPage = window.location.pathname.split('/').indexOf('preview') >= 0;
  var hasPrismicCookie = document.cookie.indexOf('prismic.preview') >= 0;
  if (isPreviewPage || hasPrismicCookie) {
    var script = document.createElement('script');
    script.src = '//static.cdn.prismic.io/prismic.min.js';
    script.type = 'text/javascript';
    document.body.appendChild(script);
  }
})();
`;

export const onRenderBody = ({ setPostBodyComponents }) => {
  setPostBodyComponents([
    <script
      // eslint-disable-next-line react/no-danger
      dangerouslySetInnerHTML={{
        __html: injectPrismaScriptHtml,
      }}
    />,
  ]);
};