stereobooster / react-snap

👻 Zero-configuration framework-agnostic static prerendering for SPAs
MIT License
5.04k stars 391 forks source link

Add documentation for analytics pixels (such as Facebook or Reddit) #415

Open kmjennison opened 4 years ago

kmjennison commented 4 years ago

Pre-rendering can break some analytics scripts, like the Reddit pixel, that assume their global is accessible before the external script loads.

Here's the Reddit pixel as an example:

<head>
  <script>
  !function(w,d){if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};p.callQueue=[];var t=d.createElement("script");t.src="https://www.redditstatic.com/ads/pixel.js",t.async=!0;var s=d.getElementsByTagName("script")[0];s.parentNode.insertBefore(t,s)}}(window,document);rdt('init','abc123');
  </script>
</head>

After pre-rendering, when the script <script src="https://www.redditstatic.com/ads/pixel.js" async> loads before the inline code, it logs this error: "Reddit Pixel Error: Pixel was not initialized. Please ensure you have included the correct pixel script in your head tag"

Other pixels, like Facebook's, are structured similarly, though whether pre-rendering causes an error depends on the pixel impelementation.

The docs have info about Google Analytics, but I didn't see anything about inline analytics code like these.

The easiest solution, like Google Analytics, is to skip running the pixel code when pre-rendering:

<script>
if (navigator.userAgent !== 'ReactSnap') {
  // pixel code here
}
</script>

If this looks good, I'd be happy to send a PR with updated documentation.