chrisvfritz / prerender-spa-plugin

Prerenders static HTML in a single-page application.
MIT License
7.32k stars 634 forks source link

How prevent some code from being pre-rendered? #355

Open mattgreenfield opened 4 years ago

mattgreenfield commented 4 years ago

Is there a way to stop certain parts of my code from being run by the pre-render-er?

I'm using Vue and have some code that sets a function on window so that I can use it as a callback in google maps;

window.myCallback = () => blah
const script = document.createElement("script");
script.src = `https://maps.googleapis.com/maps/api/js?key=${API_KEY}&callback=myCallback`;
document.querySelector("head").appendChild(script);

This is putting the google maps script tag into my prerendered HTML but it doesn't work because the callback has not been set on window. Ideally I'd like none of the above code to run when compiling the pre rendered HTML.

Thanks for your help

alvisex commented 4 years ago

I have the same problem: I want to skip one modernizr script from the prerender engine, just for the end user.

Andras1000 commented 4 years ago

Set injectProperty: '__PRERENDER_INJECTED'

See here: https://github.com/chrisvfritz/prerender-spa-plugin

Then use

if (window.__PRERENDER_INJECTED === undefined) {
  // this code snippet will be ignored in pre-render
}
alvisex commented 4 years ago

Thanks, it was very useful.

My final solution:

new PrerenderSPAPlugin({
  ....
  renderer:  new PrerenderSPAPlugin.PuppeteerRenderer({
     // The name of the property
      injectProperty: '__PRERENDER_INJECTED',
     // The values to have access to via `window.injectProperty` (the above property )
      inject: { foo:  'bar' }
    })
})

The fisrt time without the inject: { some: 'value'} it prerendered the script too, so I added the value to make it work correctly.