@times-components/lazy-load
Version:
Use IntersectionObserver to lazy load resources
1 lines • 2.78 kB
JavaScript
module.exports=function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=1)}([function(e,t){e.exports=require("react")},function(e,t,n){"use strict";n.r(t);var r=n(0);n(2);class i extends r.Component{constructor(e){if(super(e),this.isObserving=!1,this.pending=new Set,this.pendingTimer=null,this.state={clientHasRendered:!1,nodes:new Map},this.unobserved=new Set,this.unobservedTimer=null,this.registerNode=this.registerNode.bind(this),"undefined"==typeof window||!("IntersectionObserver"in window))return;this.isObserving=!0;const t={rootMargin:e.rootMargin,threshold:e.threshold};this.observer=new window.IntersectionObserver(this.handleObservation.bind(this),t)}componentDidMount(){this.setState({clientHasRendered:!0})}componentWillUnmount(){this.observer&&this.observer.disconnect(),clearTimeout(this.pendingTimer),clearTimeout(this.unobservedTimer),this.pending.clear(),this.unobserved.clear()}handleObservation(e){const t=this.props.threshold,n=this.state.nodes;e.forEach(e=>{let r=e.target,i=e.intersectionRatio;i>=t&&!n.get(r.id)?this.pending.add(r):i<t&&this.pending.has(r)&&this.pending.delete(r)}),clearTimeout(this.pendingTimer),this.pending.size&&(this.pendingTimer=setTimeout(()=>{this.pending.size&&(this.setState(e=>({nodes:new Map([...e.nodes,...[...this.pending].map(e=>[e.id,e])])})),this.pending.clear())},100))}registerNode(e){if(e){if(!this.observer){if(this.unobserved.has(e))return;return this.unobserved.add(e),clearTimeout(this.unobservedTimer),void(this.unobservedTimer=setTimeout(()=>{this.setState({nodes:new Map([...this.unobserved].map(e=>[e.id,e]))}),this.unobserved.clear()},10))}this.observer.observe(e)}}render(){const e=this.props.children,t=this.state,n=t.clientHasRendered,r=t.nodes;return e({clientHasRendered:n,isObserving:this.isObserving,observed:r,registerNode:this.registerNode})}}i.defaultProps={rootMargin:"0px"},t.default=i},function(e,t){e.exports=require("prop-types")}]);