Background:

After each front-end update, the user still stays on the page before the update after redeployment. When requesting page data, the page displays a blank screen and the following error message is displayed:

Uncaught ChunkLoadError: Loading chunk {n} failed.

why

After each update, the NAMES of JS and CSS in the HTML file on the client are inconsistent with those on the server. As a result, loading fails.

The solution

1. Listen for error events and refresh them after detecting errors

      window.addEventListener(
        'error',
        function (event) {
          if (
            event.message &&
            String(event.message).includes('Loading chunk') &&
            String(event.message).includes('failed')
          ) {
            window.location.replace(window.location.href);
          }
        },
        true,
      );
Copy the code

2. Listen for the window.console.error event

window.console.error = function () { console.log(JSON.stringify(arguments), 'window.console.error'); // custom processing};Copy the code

3. Other programmes

Such as: HTTP2.0 push mechanism/FIS3 build /webSocket notification, not tried

Note: There are good solutions can be discussed in the comments below

This article is collected in the personal work record column, dedicated to documenting some of the more interesting scenarios and problems.

Afterword.

One day later, the problem resurfaced. From a colleague in the use of the process, will not be the occurrence of the page error, error reported as follows:

Obviously, or resource loading problem, according to the truth should be able to go into our logic to refresh. However, the user feedback at that time: refresh is not the solution to the problem, force refresh can be solved.

Analysis: Why does refreshing not solve the problem? In fact, when the user failed to load the resource for network reasons at the first time, the subsequent cache flushing was removed. Therefore, the problem cannot be solved by letting the user manually refresh the resource.

Solution:

I don’t know if you noticed that the above code for listening for error events does not include CSS failure, so match the CSS load failure.

The update code is as follows:

      window.addEventListener(
        'error',
        function (event) {
          if (
            event.message &&
            String(event.message).includes('chunk') &&
            String(event.message).includes('failed')
          ) {
            window.location.replace(window.location.href);
          }
        },
        true,
      );
Copy the code

One might ask, since refreshing doesn’t solve the problem, does window.location.replace(window.location.href)?

There are many ways to refresh, but according to MDN, the location.replace () method solves this problem by replacing the current resource with the given URL.

After the