beekai-oss / react-simple-img

🌅 React lazy load images with IntersectionObserver API and Priority Hints
MIT License
989 stars 41 forks source link

Isomorphic/universel js #26

Closed millette closed 6 years ago

millette commented 6 years ago

I tried to build a site with Gatsby v2 (React static site generator). While it worked in dev, came build time I had an error because of window being undefined (server-side).

There was an easy workaround:

if (typeof window !== 'undefined') {
  initSimpleImg({ threshold: 0.5 })
}

UPDATE: my workaround was too simple. It only works if I load the page directly, not if I load another page first and then navigate to my page with lazy loaded images. Although initSimpleImg() is called in page-2, when I load page-1 I see a console output where it's called. In my case, I use SimpleImg in a component which is used by page-2, I have to figure out (with the HOC maybe) how to handle that.

Example:

I'd like to submit a patch to support client/server detection directly in your module. Interested?

bluebill1049 commented 6 years ago

hey @millette,

Can you call initSimpleImg at client entry file (eg. index.js where you call ReactDOM.render())?

thanks

bluebill1049 commented 6 years ago

yes interested your patch to support client/server! ❤️

millette commented 6 years ago

Hmm, after digging around a bit, I can't promise anything right now. It's my first real Gatsby project (with v2, in beta) and I'm not exactly sure how the pieces fit. Gatsby does SSR, since it's a static site generator. Also, I have to finish my project soon (first).

bluebill1049 commented 6 years ago

no worries @millette i will take a look the provider issue over the weekend anyhow. cheers

bluebill1049 commented 6 years ago

i will make a patch on this soon as well 🙏 thanks for reporting.

bluebill1049 commented 6 years ago

ok i have updated the initSimpleImg() method to be run only on the server. issue will be closed in the next couple days, if no issue reports :)

millette commented 6 years ago

I was able to remove my typeof window workaround, thanks again :-)

Taking the liberty to close this issue as it's easier to understand.