SoFunction
Updated on 2025-04-13

JavaScript front-end implementation of page white screen detection and solution

A white screen usually refers to the complete URL displayed in the address bar on the browser after the page is opened, but the page content cannot be rendered, and there are only white blank pages.
The causes of white screen can be roughly divided into two categories:

Resource loading issues

Code execution error

From a modern front-end perspective, both reasons are related to the widespread use of current SPA frameworks.

Resource loading issues

The resources here specifically refer to static resources such as JavaScript scripts, style sheets, and pictures, and do not include dynamic resources such as interface calls.

The white screen caused by resource loading problems can be divided into two categories: recoverable and unrecoverable.

1. Recoverable white screen

Recoverable white screens are common when entering the page for the first time. The browser cannot perform the next step because the resource is loaded too slowly or the interface request is not returned.

This white screen is usually caused by poor network conditions or poor device performance. Generally, after the browser returns, the page rendering can be restored, which can be discovered by monitoring the time of the first screen.

If the first screen time in the production environment shows an abnormal upward trend, it must be caused by the long white screen time of the page. Developers should pay attention to and check the code that has been changed in time.

2. Unrecoverable white screen

Most of the unrecoverable white screens are caused by network or cache problems.

Common examples are web applications built with SPA frameworks such as React and Vue. Once [bundle|app].js fails to access due to network reasons, the page will be white screen.

You can access any web application built by SPA framework, and reproduce it as follows: Open DevTools > Network, find , right-click and select Block request URL, and then refresh the page.

Another example is that after the SPA project is packaged, when the dist file is replaced online for the first time, some mobile phones/browsers may open the page for the first time, and the white screen may occur.

The entry file will be cached by default on the user side. Since the css/js generated by vue package are all hash values, which are different from the last file name, css/js will not be found, resulting in the white screen being generated. After the server updates the package, since the old file is deleted, the linked path is still the old file path, the file will not be found, thus the screen is white.

Code execution error

White screens caused by code execution errors are generally accompanied by blocking of functional processes, and it is difficult to fix them by waiting or page refreshing.
The reasons for this type of problem are usually caused by front-end code logic errors, or front-end data parsing logic errors caused by dirty data from the back-end interface, which eventually leads to abnormal front-end code triggering page crashes.

For example, if an exception occurs in the component in React and the error is not caught using componentDidCatch or getDerivedStateFromError externally, the DOM tree under the target node mounted by the React component render will be removed and the page will have a white screen.

Since React 16, any errors that are not caught by the error boundary will cause the entire React component tree to be uninstalled.

White screen detection

Detect whether the root node is rendered

The principle of this method is that under the current mainstream SPA framework, the DOM is generally mounted under a root node (such as <div id="app" > ). After a white screen occurs, all DOMs under the root node are usually uninstalled.

We can check whether the child elements of the root node of the page exist after the page rendering is completed. If it does not exist, we can judge that the page is in a white screen state.

This solution is concise and clear, but the disadvantages are also obvious. If the project has a skeleton screen rendering, it is impossible to determine whether the screen is white.

For example, you can use the hook function mounted or created to detect it after the page rendering is completed.

export default {
  created() {
    // Get the page root node    const rootNode = ('#app');
    // Check whether the child elements of the root node exist    if ( === 0) {
      // The page is in a white screen state      ('The page is white!  ');
    } else {
      // The page is displayed normally      ('The page is displayed normally');
    }
  },
}

Since SPA applications usually use asynchronous loading methods to load components and data, it is necessary to ensure that the page component is rendered before white screen detection is performed. If the detection is performed before the component renders, it may be misjudged as a white screen. In addition, SPA applications may have problems such as failure of asynchronous requests or loading timeouts, and the impact of these factors on white screen detection is also needed to be considered.

Mutation Observer listens for DOM changes

Mutation Observer is a way to make a callback when the DOM tree changes and can be used to listen for changes in page elements. You can use Mutation Observer to listen to changes in the DOM tree to determine whether the page is white.

But the disadvantages of this method are also obvious:

  • Impact on performance: Using Mutation Observer to listen for DOM changes will have a certain impact on browser performance, especially when the DOM tree changes frequently, it will cause callback functions to be executed frequently, affecting the page's response speed and user experience.
  • Compatibility issue: Mutation Observer's compatibility is not very good, and the support level of different browsers varies, so compatibility is required.
  • Misjudgment Problem: In some cases, the page is not a real white screen, but Mutation Observer will still misjudgment as a white screen. For example, there is a blank div element in the page. At this time, even if the page content is not loaded, it will not be judged as a white screen state.

The specific implementation steps are as follows:

Create a Mutation Observer instance and specify a callback function.

const observer = new MutationObserver((mutations) =&gt; {
  // mutations represents the change list of the DOM tree});

Bind the Mutation Observer instance to the root node and specify monitoring options.

const rootNode = ;
const observerConfig = {
  childList: true, // Listen to changes in child nodes  subtree: true, // Listen to changes in all descendant nodes  attributes: true, // Listen to the changes in node properties  characterData: true, // Listen to the changes in the text content of the node  attributeOldValue: true, // Record the value before the node attribute changes  characterDataOldValue: true, // Record the value before the node text content changes};
(rootNode, observerConfig);

Check the changes in the DOM tree in the callback function. If you find that the child elements of the root node exist, you can judge that the page is not a white screen state.

const observer = new MutationObserver((mutations) =&gt; {
  // Check whether the child elements of the root node exist  if ( &gt; 0) {
    ('The page is displayed normally');
  } else {
    ('The page is white!  ');
  }
});

Page screenshot

By taking screenshots on the web page, analyzing the screenshots to determine whether the page is white. Generally speaking, the RGB values ​​of all pixels in the screenshot can be counted. If the RGB values ​​of all pixels are the same and are very close to white (RGB(255, 255, 255)), then you can judge that the page is white screen status.

The disadvantages of this method are as follows:

The page screenshot needs to contain enough pixels to accurately detect whether the page is white. If the screenshots are not clear enough, it may lead to misjudgment.

In some cases, the page is not really a white screen, but due to some external reasons (such as network problems), the page screenshot will also be determined to be a white screen state.

If the page has a skeleton screen, it is necessary to compare the skeleton screen.

Solution

Idea: Reduce the volume after packaging (sourceMap is turned off, CDN is introduced, lazy route is loaded, components are loaded on demand)

  • Improve rendering speed
  • Optimize user experience
  • CDN resource optimization

Change all the dependency third-party npm packages to be obtained through CDN links and insert the corresponding links in them.

<body>
  <div ></div>
  <script src="/vue/2.6.10/"></script>
  <script src="/axios/0.19.0-beta.1/"></script>
  <script src="/vuex/3.1.0/"></script>
  <script src="/vue-router/3.0.2/"></script>
  <script src="/element-ui/2.6.1/"></script>
</body>

Configure the externals property in

 = {
 ···
    externals: {
      'vue': 'Vue',
      'vuex': 'Vuex',
      'vue-router': 'VueRouter',
      'axios':'axios',
      'element-ui': 'ElementUI'
    }
 }

Uninstall npm packages related to dependencies

npm uninstall xxx

Use gzip compression

Front-end processing:

// npm i compression-webpack-plugin -S
const CompressionPlugin = require('compression-webpack-plugin');

​​​​​​​ = {
  productionSourceMap: false,
  configureWebpack: config =&gt; {
    if (.NODE_ENV === 'production') {
      return {
        plugins: [
          new CompressionPlugin({
            // Match specifications            test: /\.js$|\.html$|\.css$|\.png$/,
            // How much does the file exceed? Unit Byte            threshold: 10240,
            // Whether to delete the source file (recommended not to delete it)            deleteOriginalAssets: false
          })
        ],
      }
    }
  },
}

You also need to enable gzip compression in nginx, for example:

 gzip on;
 gzip_static on; // When there is a .gzip format js file, static files are preferred gzip_min_length  10k; // Turn on the minimum size of gzip compression gzip_buffers     4 16k;
 gzip_http_version 1.1;
 gzip_comp_level 6;
 gzip_types     text/plain application/javascript application/x-javascript text/javascript text/css application/xml;
 gzip_vary on;
 gzip_proxied   expired no-cache no-store private auth;
 gzip_disable   "MSIE [1-6]\.";

Notice:

When nginx enables gzip compression, regardless of whether the files packaged from the front end are compressed, the js files loaded on the website are compressed in real time by nginx.

When gzip_static off, the js compressed files uploaded by the front end (those in gzip formats) are of no use.

When gzip_static on, priority is given to loading the front-end packaged gzip compressed file. If the file is not found, nginx will compress in real time and then pass it to the browser.

This is the article about JavaScript front-end implementation of white screen detection and solution. For more related content on white screen of JavaScript page, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!