页面交互后立即响应 Lazyload

React Lazyload as soon as page interacted with

我正在构建一个使用实时聊天的 React 站点,并且正在使用 react-livechat 包。我已将它与 react-lazyload 插件配对,以试图防止它对页面加载时间产生不利影响。

我现在正在尝试找出一种方法,以便在与页面交互时立即加载实时聊天组件。目前它仅在页面滚动到组件的设定距离内时呈现,默认情况下是页面的页脚。这确实可以防止页面加载受到影响,但需要用户在加载组件之前滚动一定距离。理想情况下,它会从与页面的任何交互中加载。

import React, { Component } from 'react';

import LiveChat from 'react-livechat';
import LazyLoad from 'react-lazyload';

class App extends Component {


  render() {
    return (
      <div className="App">
        ...
        <LazyLoad once>
          <LiveChat license={'xxxxxx'} />
        </LazyLoad>
        ...
      </div>
    );
  };
}

export default App;

我设法通过解决方法获得此行为,并在一段时间后加载组件。我发现 10 秒可以很好地确保即使在移动设备上也能完全呈现所有内容。


// App.js
import React, { Component } from 'react';
import LazyLiveChat from './components/utils/lazyLiveChat';

class App extends Component {

  constructor() {
    super();
    this.state = { loadLiveChat: false };
  }

  componentDidMount() {
    setTimeout(() => this.setState({loadLiveChat: true}), 10000);
  }

  render() {
    return (
      <div className="App">
        ...
        <LazyLiveChat loadChat={this.state.loadLiveChat} />
        ...
      </div>
    );
  };
}

export default App;

// lazyLiveChat.js
import React, { Component } from 'react';
import LiveChat from 'react-livechat';

class LazyLiveChat extends Component {

  render() {
    if (this.props.loadChat) {
      return (
        <LiveChat license={xxxxxx} />
      );
    }
    return null;
  }
}

export default LazyLiveChat;