I simply don't know how. I'm importing all my other assets like import React from 'react' to get them bundled and being able to reference them. I tried importing it like import 'lazysizes' but that didn't work either.
Also how to manage importing plugins on top of that.
And to be even more annoying I need a way to get it working on the server too. It's ok to run it only on the client but I need to be able to import in somehow on the server.
@sarukuku does this work? This works in my applications:
import lazySizes from 'lazysizes';
i.e.
lazySizes.loader.unveil(myImageElement);
Just like this:
import React from 'react';
import lazySizes from 'lazysizes';
const Playground = () => (
<img
data-sizes="auto"
data-src="http://img.release.1yd.me/Fnq3JmmOan-yAHtJHk-n9-o3Qqbr"
className="lazyload"
alt="lazySizes"
/>
);
export default Playground;
Ok! I'll try that. How about the plugins? I need to load the respimg plugin too?
I've also noticed that when react components receive new props and they are mapped to the data-srcset attribute lazysizes initializes the image only once. It doesn't update the srcset attribute thought the value of data-srcset changes after the initial init.
Also, does importing lazysizes like that "work" on the server side? Mainly I'm interested can it cope on the server. It ofc. can't do anything at the server but will it fail is my question.
Tested, you can't import lazysizes on the server. It will fail with
ReferenceError: window is not defined
at Object.<anonymous> ({...}/node_modules/lazysizes/lazysizes.js:7:3)
Importing plugins:
import 'lazysizes/plugins/attrchange/ls.attrchange';
import 'lazysizes';
You can not import lazySizes on the server. In my eyes you don't need to import lazysizes in every component. simply import it unnamed in your clients-only script and you are done.
If you change the data-srcset you also need to re-add the lazyload class. In case this is to complicated. You can use the attrchange plugin.
Thanks @aFarkas for answering. Requiring the attrchange plugin resolves the problem with the updating data-srcset attribute. I ended up code like this to only require lazysizes on the client:
if (!isServer) {
require('lazysizes/plugins/attrchange/ls.attrchange.js')
require('lazysizes/plugins/respimg/ls.respimg.js')
require('lazysizes')
}
Most helpful comment
Importing plugins:
You can not import lazySizes on the server. In my eyes you don't need to import lazysizes in every component. simply import it unnamed in your clients-only script and you are done.
If you change the
data-srcsetyou also need to re-add thelazyloadclass. In case this is to complicated. You can use the attrchange plugin.