Closed moritzbastian closed 3 years ago
Sorry, but I don't follow. What is the problem you're experiencing exactly? Do blurry images show up, but aren't replaced by the normal images? You'll have to use the included JS library for that.
Exactly!
I put the "useLazyload.js" file in my footer. Is that correct?
No, it has to be initialized first. Please see the instructions section of the readme.
The JS library is primarily intended to be used alongside a build chain (with bundling).
Edit: You can, however, just create a plain JS file with the initialization code in it and link it in your footer via <script src="/assets/js/lazyload.js" type="module"></script>
. It won't be performant, but it will work. 🙂
I also tried the initialising code from the readme. With that I'll get "Uncaught SyntaxError: Cannot use import statement outside a module".
I'm not very good in JS - probably just a dumb mistake by me.
Yes, you'll have to add the type="module"
attribute. But I have a better solution – I have prebundled the library for you. Take this code:
(()=>{var z=!("onscroll"in window)||/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),b=(t,o=250)=>{let e;return(...s)=>{e&&clearTimeout(e),e=setTimeout(()=>{e=null,t(...s)},o)}},c=t=>{let o=t.dataset.src;o&&(t.src=o);let e=t.dataset.srcset;if(e){t.srcset=e;let s=t.dataset.sizes;s&&(t.sizes=s==="auto"?`${t.offsetWidth}px`:s)}t.dataset.loaded="true"},d=t=>t.dataset.loaded==="true",g=t=>{for(let o of t)o.dataset.sizes==="auto"&&(o.sizes=`${o.offsetWidth}px`)},w=t=>(o,e)=>{for(let s of o)if(s.intersectionRatio>0||s.isIntersecting){let{target:n}=s;if(e.unobserve(n),d(n))continue;c(n),t(n)}},v=(t,o=document)=>t instanceof Element?[t]:t instanceof NodeList?[...t]:o.querySelectorAll(t);function f(t="[data-lazyload]",o={}){let{root:e,rootMargin:s="0px",threshold:n=0,loaded:a=()=>{}}=o,u=new IntersectionObserver(w(a),{root:e,rootMargin:s,threshold:n});return{observe(){let r=v(t,e);for(let i of r)if(!d(i)){if(z){c(i),a(i);continue}u.observe(i)}let l=b(()=>g(r),100);window.addEventListener("resize",l)},triggerLoad(r){d(r)||(c(r),a(r))},observer:u}}var L=f();L.observe();})();
Just save it to a filename of your liking (e. g. lazyloading.min.js
) and include it in your footer. All done. 🙂
The prebundled libary is working perfectly. Thanks Johann!
If anyone reads this and still wonders. From version 1.3 of this plugin forward, the lazy loading library can be used without a build step:
Simply load it from a CDN:
<script src="https://unpkg.com/loadeer" defer init></script>
defer
attribute makes the script execute after HTML content is parsed.init
attribute tells Loadeer.js to automatically initialize and watch all elements that have a data-lazyload
attribute.
Hi,
I have truobles getting the High-res image up. Blurry is working fine. I'll try fetching the images in a foreach.