electerious / basicScroll

Standalone parallax scrolling for mobile and desktop with CSS variables.
https://basicscroll.electerious.com
MIT License
3.63k stars 148 forks source link

Support server side rendering #32

Closed piersolenski closed 5 years ago

piersolenski commented 5 years ago

Getting a requestAnimationFrame is not defined error in non-browser environments, such as when Server Side Rendered or during a Static Site build.

piersolenski commented 5 years ago

I imagine window and document might need to be checked for as well...

stratboy commented 5 years ago

as far as I know, requestAnimationFrame is not available in node.

electerious commented 5 years ago

Is there a way to only run basicScroll on the client? I guess this would be better than adding window, document and requestAnimationFrame checks as basicScroll is made for the client. But I get your point. Just thinking about what would be best.

bdrtsky commented 5 years ago

@superfunkminister you can do this check by yourself. In Nuxt we have process.browser for that.

But it's worth to mention that even with this check I had issues with basicScroll with SSR, which I did not had with other animation libs. If interested I can reproduce this.

electerious commented 5 years ago

It's because basicScroll starts as soon as you include it: https://github.com/electerious/basicScroll/blob/master/src/scripts/main.js#L452

When we implement a window and document check, basicScroll should at least output a warning so it's not just doing nothing silently.

piersolenski commented 5 years ago

Yep, my current way around the problem is to use this kind of pattern in React:

componentDidMount() {
  let basicScroll;
  if (typeof window !== 'undefined') {
    basicScroll = require('basicscroll');
    // Do stuff with basicScroll
  }
}

Obviously this is a very React specific example, and there's a bunch of other ways around it depending on your stack... But the easiest fix to stop this kind of issue reoccurring, and as a developer constantly having to implement a workaround, is to make the library itself isomorphic. For example, https://github.com/akiran/react-slick (also made for the client) handles the problem in the following way https://github.com/akiran/react-slick/blob/48c93ed36cfb58991e6bf4d34a1a588094281d12/src/utils/innerSliderUtils.js#L821

electerious commented 5 years ago

v3.0.1 includes a window check and should work fine when executed in a non-browser environment: https://github.com/electerious/basicScroll/blob/master/CHANGELOG.md#301---2018-12-20

Please let me know when it isn't work as expected.