preactjs / next-plugin-preact

Next.js plugin for preact X
395 stars 9 forks source link

lazy loading in Image component from react-datocms not work #17

Open nephlin7 opened 3 years ago

nephlin7 commented 3 years ago

I'm using NextJS v10 with DatoCMS. Currently, I want to use this plugin to improve the bundle sizes but I realized that the lazy loading in the Image component from https://github.com/datocms/react-datocms not work.

jesster2k10 commented 3 years ago

I had a similar issue using a custom setup with LazySizes. My code looked something like this:

const LazyImage = ({
  src,
  placeholderSrc,
  animationType = 'blur',
  lazyMinHeight,
  lazyMaxWidth,
  ...props
}: LazyImageProps) => (
  <div
    className={animationType === 'blur' && 'blur-up-container'}
    css={{ width: '100%', minHeight: lazyMinHeight }}
  >
    <Img
      {...props}
      className={cs(
        'lazyload',
        'js-only',
        animationType === 'blur' && 'blur-up',
      )}
      data-src={src}
      src={placeholderSrc}
      css={{
        '&.lazyload': {
          width: '100%',
          minHeight: lazyMinHeight,
        },
      }}
    />
    <noscript>
      <Img {...props} src={src} />
    </noscript>
  </div>
);

Where I was basically hiding the lazy loaded image using a .js-only tag (since it only works with JS enabled). The issue lies with preact somehow thinking that javascript was disabled, when it was actually disabled and therefore evaluating this:

<noscript>
          <style>{`
          .js-only {
            display: none;
          }
        `}</style>
        </noscript>

Which caused my images to be hidden. To resolve this, I just had to avoid rendering that piece of code on the client. So that was changed to:

{typeof window === 'undefined' && (
        <noscript>
          <style>{`
          .js-only {
            display: none;
          }
        `}</style>
        </noscript>
      )}

You would want to check out this issue for reference. https://github.com/preactjs/preact/issues/2797

sventschui commented 3 years ago

@jesster2k10 preact indeed differs a bit from React's handling of noscript tags.

@nephlin7 if you provide a reproduction case we will be able to look into your issue. I am not familiar with react-datocms