magic-akari / seamless-scroll-polyfill

Scroll Behavior polyfill
https://www.npmjs.com/package/seamless-scroll-polyfill
MIT License
159 stars 11 forks source link

Reference to document causes GatsbyJS build to fail #108

Closed alandickinson closed 3 years ago

alandickinson commented 3 years ago

Hi again! I'm using this polyfill in a Gatsby project, which supports server side rendering. So the code runs outside of a browser, and doesn't have access to the document or window objects. This line is causing gatsby builds to fail because it references the document object without checking first if it exists: https://github.com/magic-akari/seamless-scroll-polyfill/blob/5d7f8b61896671f8b684d03bf8fa563a5127eca3/src/common.ts#L7

alandickinson commented 3 years ago

I've solved this in my project for now by checking that window is defined before running any of the polyfill code.

typeof window !== 'undefined' && elementScrollIntoViewPolyfill();
if (typeof window !== 'undefined') {
    tabRefs.current[index].scrollIntoView({
        behavior: "smooth",
        inline: "center",
        block: "nearest",
        // set a custom duration used by the polyfill
        duration: 150
    });
}
magic-akari commented 3 years ago

All the code is side-effect free(except auto-polyfill.js). You can import it safely. But before calling the polyfill function, you have to make sure the code runs in browser.

Example:

if(isBrowser()){
  elementScrollIntoViewPolyfill();
}