react-lazyload 源码解析
生活随笔
收集整理的這篇文章主要介紹了
react-lazyload 源码解析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
懶加載也叫延遲加載,指的是在長網頁中延遲加載dom(jquery時期常用于延遲加載圖片,現在也會用于延遲加載復雜組件),是優化網頁性能的方式之一。當dom不在可視區內時,dom使用占位符展示,當到達可視區后再進行真實dom加載渲染。
所以我們首先要判斷我們想要加載的內容是否在可視區域。這里應該有一個父級元素和子元素(如果沒有父元素,瀏覽器適口就充當父級元素的角色)來定義”可視區域”的大小。
react-lazyload通過監聽各個react生命周期,監聽scroll,resize兩個事件執行相應的操作
var LazyLoad = function (_Component) {..._createClass(LazyLoad, [{key: 'componentDidMount',value: function componentDidMount() {if (needResetFinalLazyLoadHandler) {(0, _event.off)(scrollport, 'scroll', finalLazyLoadHandler, passiveEvent);(0, _event.off)(window, 'resize', finalLazyLoadHandler, passiveEvent);finalLazyLoadHandler = null;}...if (this.props.overflow) {var parent = (0, _scrollParent2.default)(this.ref);if (parent && typeof parent.getAttribute === 'function') {var listenerCount = 1 + +parent.getAttribute(LISTEN_FLAG);if (listenerCount === 1) {parent.addEventListener('scroll', finalLazyLoadHandler, passiveEvent);}parent.setAttribute(LISTEN_FLAG, listenerCount);}} else if (listeners.length === 0 || needResetFinalLazyLoadHandler) {var _props = this.props,scroll = _props.scroll,resize = _props.resize;if (scroll) {(0, _event.on)(scrollport, 'scroll', finalLazyLoadHandler, passiveEvent);}if (resize) {(0, _event.on)(window, 'resize', finalLazyLoadHandler, passiveEvent);}}}} /*** 檢測元素是否在視口中可見,如果是,則將``visible''狀態設置為true。如果將``once''屬性設置為true,則在checkVisible之后移除組件作為偵聽器* @param {React} component 響應滾動和調整大小的React組件 */ var checkVisible = function checkVisible(component) {var node = component.ref;if (!(node instanceof HTMLElement)) { // 首先判斷是不是HTMLElement元素,如果不是直接返回return; }var parent = (0, _scrollParent2.default)(node); // 獲取parent// 判斷通過那種方式來進行判定(和父元素做比較,和視圖做比較)var isOverflow = component.props.overflow && parent !== node.ownerDocument && parent !== document && parent !== document.documentElement;// checkOverflowVisible:檢查`component`在溢出容器`parent`中是否可見// checkNormalVisible:檢查`component`在文檔中是否可見var visible = isOverflow ? checkOverflowVisible(component, parent) : checkNormalVisible(component);// 所以我們如果要用父元素做可視區域最好是設置overflow這個屬性if (visible) {// 如果以前可見,請避免額外的渲染if (!component.visible) {if (component.props.once) {pending.push(component);}component.visible = true;component.forceUpdate();}} else if (!(component.props.once && component.visible)) {component.visible = false;if (component.props.unmountIfInvisible) {component.forceUpdate();}} };參考:https://github.com/twobin/react-lazyload
總結
以上是生活随笔為你收集整理的react-lazyload 源码解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ProE 工程图教程系列-4 ProE不
- 下一篇: 快速建站的实现框架