React如何展示Loading加载页面

React如何展示Loading加载页面

hash070 1,106 2023-01-02

简介

像React这样开发的大前端Web应用有一个通病,就是首屏加载时间较长,而且在加载过程中用户看到的都是白屏,此时如果你的服务器或者用户自己的带宽过小的话可能会让用户以为这个网站挂掉了,从而导致流量损失。下图是Twitter网站的加载页面,像Twitter这样弄一个Loading页面或者图片也许就能在页面加载缓慢时留住用户。

image-20230102150244969

本文用来记录一下如何实现在大前端JS加载前呈现一个Loading页面。

实现方法

实现方法很简单,直接在项目根目录的index.html中编写加载页面就行了。

建议在idroot的根节点中编写加载页面

因为在根节点中编写的内容,会在React前端JS加载完毕并开始渲染时被自动清除,正好省去了手动清理Loading的麻烦。

比如我把root div 改成下面这样:

    <div id="root">
      <div id="loading">
        <img src="https://img.hash070.top/i/63b2693d4f9c3.webp" width="72px" alt="logo">
        <p style="text-align: center">Loading</p>
      </div>
    </div>

那么React项目首屏加载时的效果就是这样的:

image-20230102150628526

React开始渲染时确实也会被自动移除,感觉还不错。

参考链接:https://stackoverflow.com/questions/40987309/react-display-loading-screen-while-dom-is-rendering

More

刚刚的只是放了一个图片,也许有同学觉得还是差点意思,那么也许我们可以整一个CSS动画,让Loading更好看一点?

首先把css写到头部的style块中:

    <style>
	  .loader {
        border: 6px solid #e4f2fb;
        border-radius: 50%;
        border-top: 6px solid #1d9aee;
        width: 32px;
        height: 32px;
        -webkit-animation: spin 0.4s linear infinite; /* Safari */
        animation: spin 0.4s linear infinite;
      }

      /* Safari */
      @-webkit-keyframes spin {
        0% { -webkit-transform: rotate(0deg); }
        100% { -webkit-transform: rotate(360deg); }
      }

      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    </style>

然后在根div里这样写

    <div id="root">
		<div id="loading">
       	 <img src="https://img.hash070.top/i/63b2693d4f9c3.webp" style="margin:0 auto;display: block" width="72px" alt="logo">
        	<div style="margin:20px auto" class="loader"></div>
      	</div>
	</div>

实现效果:

image-20230102153956207

更多现成的CSS Loader:

参考链接:https://www.w3schools.com/howto/howto_css_loader.asp