Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[React] Network-aware code-splitting #2

Closed
addyosmani opened this issue Jul 11, 2019 · 0 comments
Closed

[React] Network-aware code-splitting #2

addyosmani opened this issue Jul 11, 2019 · 0 comments

Comments

@addyosmani
Copy link
Collaborator

Goal

Combine the Network Information API and dynamic imports in order to dynamically load a lightweight or heavy version of a component based on the user's effective connection type.

Background

The Network Information API summarizes the performance of a users network connection. This allows us to customize how we deliver experiences based on how slow or fast a connection is.

One of the signals NetInfo provides us is ECT - the Effective Connection Type. It doesn't inform if you are connected to WiFi or are on a cellular connection - it's more useful. ECT analyzes the latency of the current connection and determines which network profile it resembles the most. If you are on slow coffeeshop WiFi but your effective speed is 2G, ECT will report this as the best approximation of your effective connection speed. Valid values for ECT are 4g, 3g, 2g, and slow-2g. I typically bucket these into fast (4G), medium (3G) and slow (2G, slow-2G).

One could serve a light component on 2G, slow-2G, medium on 3G and a heavy component on 4G. Loosely, this should work:

import React, { Suspense } from 'react';
import './App.css';

const Sample = React.lazy(() => {
  return new Promise(resolve => {
    navigator.connection ? resolve(navigator.connection.effectiveType) : resolve(null)
  }).then((effectiveType) => {
    switch (effectiveType) {
      case "4g":
        return import(/* webpackChunkName: "heavy" */ "./Heavy.js");
        break;
      case "3g":
        return import(/* webpackChunkName: "medium" */ "./Medium.js");
        break;
      case "2g":
        return import(/* webpackChunkName: "light" */ "./Light.js");
        break;
      default:
        return import(/* webpackChunkName: "medium" */ "./Medium.js")
    }
  });
});

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <Suspense fallback={<div>Loading...</div>}>
          <Sample />
        </Suspense>
      </header>
    </div>
  );
}

export default App;

Sample

We should demonstrate how the above pattern can be used with create-react-app in order to implement network-aware code-splitting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant