javascript 根据网络速度加载CSS

eblbsuwk  于 4个月前  发布在  Java
关注(0)|答案(1)|浏览(65)

在Gmail中,当我的互联网速度很慢时,它会显示一个颜色、图标和动画都较少的基本页面。我希望我的React项目也能做类似的事情。我的项目有两个全局SCSS文件,index.scssindex-lite.scss。当网络速度很慢时,我如何让它加载更简单的CSS文件来让我的First Contentful Paint (FCP)更快?
下面是我的主要index.ts组件代码。

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'),
);

字符串

pu3pd22g

pu3pd22g1#

使用js navigator connection API来检查网速慢,并根据速度动态加载CSS文件。

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);
}

字符串
在上面的代码片段中,effectiveType属性提供了一个表示连接的有效类型的字符串,它可以是'slow-2g'、'2g'、'3g'或'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)

相关问题