React - Display loading screen while DOM is rendering?

前端 未结 19 1585
我在风中等你
我在风中等你 2020-11-28 00:29

This is an example from Google Adsense application page. The loading screen displayed before the main page showed after.

I don\'t know how to do the same th

相关标签:
19条回答
  • 2020-11-28 00:45

    This will happen before ReactDOM.render() takes control of the root <div>. I.e. your App will not have been mounted up to that point.

    So you can add your loader in your index.html file inside the root <div>. And that will be visible on the screen until React takes over.

    You can use whatever loader element works best for you (svg with animation for example).

    You don't need to remove it on any lifecycle method. React will replace any children of its root <div> with your rendered <App/>, as we can see in the GIF below.

    Example on CodeSandbox

    index.html

    <head>
      <style>
        .svgLoader {
          animation: spin 0.5s linear infinite;
          margin: auto;
        }
        .divLoader {
          width: 100vw;
          height: 100vh;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      </style>
    </head>
    
    <body>
      <div id="root">
        <div class="divLoader">
          <svg class="svgLoader" viewBox="0 0 1024 1024" width="10em" height="10em">
            <path fill="lightblue"
              d="PATH FOR THE LOADER ICON"
            />
          </svg>
        </div>
      </div>
    </body>
    
    

    index.js

    Using debugger to inspect the page before ReactDOM.render() runs.

    import React from "react";
    import ReactDOM from "react-dom";
    import "./styles.css";
    
    function App() {
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }
    
    debugger; // TO INSPECT THE PAGE BEFORE 1ST RENDER
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    
    0 讨论(0)
  • 2020-11-28 00:45

    I'm using react-progress-2 npm package, which is zero-dependency and works great in ReactJS.

    https://github.com/milworm/react-progress-2

    Installation:

    npm install react-progress-2

    Include react-progress-2/main.css to your project.

    import "node_modules/react-progress-2/main.css";

    Include react-progress-2 and put it somewhere in the top-component, for example:

    import React from "react";
    import Progress from "react-progress-2";
    
    var Layout = React.createClass({
    render: function() {
        return (
            <div className="layout">
                <Progress.Component/>
                    {/* other components go here*/}
                </div>
            );
        }
    });
    

    Now, whenever you need to show an indicator, just call Progress.show(), for example:

    loadFeed: function() {
        Progress.show();
        // do your ajax thing.
    },
    
    onLoadFeedCallback: function() {
        Progress.hide();
        // render feed.
    }
    

    Please note, that show and hide calls are stacked, so after n-consecutive show calls, you need to do n hide calls to hide an indicator or you can use Progress.hideAll().

    0 讨论(0)
  • 2020-11-28 00:46

    If anyone looking for a drop-in, zero-config and zero-dependencies library for the above use-case, try pace.js (http://github.hubspot.com/pace/docs/welcome/).

    It automatically hooks to events (ajax, readyState, history pushstate, js event loop etc) and show a customizable loader.

    Worked well with our react/relay projects (handles navigation changes using react-router, relay requests) (Not affliated; had used pace.js for our projects and it worked great)

    0 讨论(0)
  • 2020-11-28 00:46

    Edit your index.html file location in the public folder. Copy your image to same location as index.html in public folder. And then replace the part of the contents of index.html containing <div id="root"> </div> tags to the below given html code.

    <div id="root">  <img src="logo-dark300w.png" alt="Spideren" style="vertical-align: middle; position: absolute;
       top: 50%;
       left: 50%;
       margin-top: -100px; /* Half the height */
       margin-left: -250px; /* Half the width */" />  </div>
    

    Logo will now appear in the middle of the page during the loading process. And will then be replaced after a few seconds by React.

    0 讨论(0)
  • 2020-11-28 00:46

    The starting of react app is based on the main bundle download. React app only starts after the main bundle being downloaded in the browser. This is even true in case of lazy loading architecture. But the fact is we cannot exactly state the name of any bundles. Because webpack will add a hash value at the end of each bundle at the time when you run 'npm run build' command. Of course we can avoid that by changing hash settings, but it will seriously affect the cache data problem in the Browser. Browsers might not take the new version because of the same bundle name. . we need a webpack + js + CSS approach to handle this situation.

    change the public/index.html as below

    <!DOCTYPE html>
    <html lang="en" xml:lang="en">
    
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=3.0, shrink-to-fit=no">
      <meta name="theme-color" content="#000000">
      <!--
          manifest.json provides metadata used when your web app is added to the
          homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
        -->
      <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
      <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
      <style>
     .percentage {
          position: absolute;
          top: 50%;
          left: 50%;
          width: 150px;
          height: 150px;
          border: 1px solid #ccc;
          background-color: #f3f3f3;
          -webkit-transform: translate(-50%, -50%);
              -ms-transform: translate(-50%, -50%);
                  transform: translate(-50%, -50%);
          border: 1.1em solid rgba(0, 0, 0, 0.2);
          border-radius: 50%;
          overflow: hidden;
          display: -webkit-box;
          display: -ms-flexbox;
          display: flex;
          -webkit-box-pack: center;
              -ms-flex-pack: center;
                  justify-content: center;
          -webkit-box-align: center;
              -ms-flex-align: center;
                  align-items: center;
        }
    
        .innerpercentage {
          font-size: 20px;
        }
      </style>
      <script>
        function showPercentage(value) {
          document.getElementById('percentage').innerHTML = (value * 100).toFixed() + "%";
        }
        var req = new XMLHttpRequest();
        req.addEventListener("progress", function (event) {
          if (event.lengthComputable) {
            var percentComplete = event.loaded / event.total;
            showPercentage(percentComplete)
            // ...
          } else {
            document.getElementById('percentage').innerHTML = "Loading..";
          }
        }, false);
    
        // load responseText into a new script element
        req.addEventListener("load", function (event) {
          var e = event.target;
          var s = document.createElement("script");
          s.innerHTML = e.responseText;
          document.documentElement.appendChild(s);
          document.getElementById('parentDiv').style.display = 'none';
    
        }, false);
    
        var bundleName = "<%= htmlWebpackPlugin.files.chunks.main.entry %>";
        req.open("GET", bundleName);
        req.send();
    
      </script>
      <!--
          Notice the use of %PUBLIC_URL% in the tags above.
          It will be replaced with the URL of the `public` folder during the build.
          Only files inside the `public` folder can be referenced from the HTML.
    
          Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
          work correctly both with client-side routing and a non-root public URL.
          Learn how to configure a non-root public URL by running `npm run build`.
        -->
    
      <title>App Name</title>
      <link href="<%= htmlWebpackPlugin.files.chunks.main.css[0] %>" rel="stylesheet">
    </head>
    
    <body>
      <noscript>
        You need to enable JavaScript to run this app.
      </noscript>
      <div id="parentDiv" class="percentage">
        <div id="percentage" class="innerpercentage">loading</div>
      </div>
      <div id="root"></div>
      <!--
          This HTML file is a template.
          If you open it directly in the browser, you will see an empty page.
    
          You can add webfonts, meta tags, or analytics to this file.
          The build step will place the bundled scripts into the <body> tag.
    
          To begin the development, run `npm start` or `yarn start`.
          To create a production bundle, use `npm run build` or `yarn build`.
        -->
    </body>
    
    </html>

    In your production webpack configuration change the HtmlWebpackPlugin option to below

     new HtmlWebpackPlugin({
              inject: false,
    ...
    

    You may need to use 'eject' command to get the configuration file. latest webpack might have the option to configure the HtmlWebpackPlugin without ejecting project.

    0 讨论(0)
  • 2020-11-28 00:46

    You can easily do that by using lazy loading in react. For that you have to use lazy and suspense from react like that.

    import React, { lazy, Suspense } from 'react';
    
    const loadable = (importFunc, { fallback = null } = { fallback: null }) => {
      const LazyComponent = lazy(importFunc);
    
      return props => (
        <Suspense fallback={fallback}>
          <LazyComponent {...props} />
        </Suspense>
      );
    };
    
    export default loadable;
    

    After that export your components like this.

    export const TeacherTable = loadable(() =>
      import ('./MainTables/TeacherTable'), {
        fallback: <Loading />,
      });
    

    And then in your routes file use it like this.

     <Route exact path="/app/view/teachers" component={TeacherTable} />
    

    Thats it now you are good to go everytime your DOM is rendering your Loading compnent will be displayed as we have specified in the fallback property above. Just make sure that you do any ajax request only in componentDidMount()

    0 讨论(0)
提交回复
热议问题