javascriptreactjsoptimizationcore-web-vitals

Load CSS based on network speed


In Gmail, when my internet is slow, it shows a basic page with fewer colors, icons and animations. I want my React project to do something similar. I have two global SCSS files for my project, index.scss and index-lite.scss. How can I make it load the simpler CSS file when the network is slow to make my First Contentful Paint (FCP) faster?

Here is my main index.ts component code.

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { configure } from 'axios-hooks';

import App from './components/App';
import API from './utils/api';
import store from './store';
import './index.scss';  **// or import './index-lite.scss';**


configure({ axios: API });

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root'),
);

Solution

  • use js navigator connection API to check slow internet speed and load the CSS files dynamically based on speed.

    if (navigator.connection) {
      console.log(`Effective network type: ${navigator.connection.effectiveType}`);
      console.log(`Downlink Speed: ${navigator.connection.downlink}Mb/s`);
      console.log(`Round Trip Time: ${navigator.connection.rtt}ms`);
    } else {
      console.log('Navigator Connection API not supported);
    }
    

    In the code snippet above, the effectiveType attribute provides a string that represents the effective type of the connection, and it could be 'slow-2g', '2g', '3g', or '4g'.

    const fileref = document.createElement("link");
    const filename = 'style.css' # based on speed
    fileref.rel = "stylesheet";
    fileref.type = "text/css";
    fileref.href = filename;
    document.getElementsByTagName("head")[0].appendChild(fileref)