svelte / sapper : ReferenceError: IntersectionObserver is not defined

1k Views Asked by At

I am using the svelte-intersection-observer module to try to do lazy loading with a sapper setup. When the site first loads with the demo code from the node library intro page, it displays this error on the main view:

500
IntersectionObserver is not defined

ReferenceError: IntersectionObserver is not defined
    at eval (webpack:///./node_modules/svelte-intersection-observer/src/IntersectionObserver.svelte?:47:2)
    at Object.$$render (webpack:///./node_modules/svelte/internal/index.mjs?:1268:22)
    at eval (webpack:///./src/routes/index.svelte?:48:175)
    at Object.$$render (webpack:///./node_modules/svelte/internal/index.mjs?:1268:22)
    at Object.default (webpack:///./src/node_modules/@sapper/internal/App.svelte?:35:417)
    at eval (webpack:///./src/routes/_layout.svelte?:23:38)
    at Object.$$render (webpack:///./node_modules/svelte/internal/index.mjs?:1268:22)
    at eval (webpack:///./src/node_modules/@sapper/internal/App.svelte?:33:152)
    at $$render (webpack:///./node_modules/svelte/internal/index.mjs?:1268:22)
    at Object.render (webpack:///./node_modules/svelte/internal/index.mjs?:1276:26)

if I click any other tab and go back to the page using the intersection observer, it works perfectly. I just can't figure out how to fix it to make it work with sapper. Thank you!

2

There are 2 best solutions below

1
On BEST ANSWER

This is a bug in svelte-intersection-observer — it needs to be modified such that it can be used in server-side rendering without crashing. I recommend raising an issue on the tracker.

0
On

In Sapper, the first page loaded in the browser is SSR'd, so your code is executed in Node. The subsequent page changes are rendered in the browser. So, if it crashes on the first page but works on subsequent page changes it looks like your library doesn't work in Node -- which also seems expected if it's a lib that measures things on screen. In this case, the solution is to put your browser only code in an onMount hook in your components, so that it only runs in the browser.