gpt4 book ai didi

javascript - Angular PWA 更新太慢

转载 作者:行者123 更新时间:2023-12-04 11:32:57 25 4
gpt4 key购买 nike

我有一个 Angular 8 PWA 应用程序正在生产中。我会定期进行大量更新,因此我需要找到一种方法让用户在打开应用程序时获取这些更新。

如果没有特殊操作,应用程序将不会更新。如果您在浏览器上打开该应用程序,它将显示您上次打开该应用程序时的版本,即使我已将新捆绑包推送到生产环境。这似乎是 PWA 功能的不幸结果。

我正在使用 AWS Amplify 进行托管。

为了解决这个问题(我曾问过一个关于它的问题 here),我尝试使用 swUpdate。

问题是它工作得太慢了。如果有更新,它将重新加载浏览器——但这需要一段时间。用户打开应用程序后通常需要几秒钟才能重新加载。因此,您打开应用程序,4 到 6 秒后应用程序重新加载新版本。

有没有办法让 swUpdate 更快?或者另一种加载新应用版本的方法?

这是我的代码,我认为这是一个简单的实现:

app.component.ts:

import { Component } from '@angular/core';
import { SwUpdate } from '@angular/service-worker';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {

constructor(private swUpdate: SwUpdate) {
title = 'Great App'

swUpdate.available.subscribe(event => {
swUpdate.activateUpdate().then(() => {
window.location.reload();
console.log('there is an Update! Reloading now.')
});
})

if (!this.swUpdate.isEnabled) {
console.log('Not going to update');
}
}

但这并不能很好地工作,因为重新加载通常会在用户进入应用程序后几秒钟发生(即使在良好的互联网连接情况下)。

我知道我也可以向人们显示一条消息,说“想用新版本刷新吗?”但这并不能解决当前 swUpdate 工作速度有多慢的根本问题。

最佳答案

对于仍然遇到此问题的任何人,这是我为减少延迟所做的事情:

  • 在 APP_INITIALIZER 而不是 AppComponent 中检查更新,以便更早完成检查
  • 使用 checkForUpdate方法

  • 在您的 app.module.ts添加初始化函数:
    { provide: APP_INITIALIZER, useFactory: checkForUpdates, multi: true, deps: [SwUpdate /* Add whatever dependency is required here */] },
    该函数应如下所示:
    export const checkForUpdates = (swUpdate: SwUpdate): (() => Promise<any>) => {
    return (): Promise<void> =>
    new Promise((resolve) => {
    swUpdate.checkForUpdate();

    swUpdate.available.subscribe(() => {
    window.location.reload();
    });

    resolve();
    });
    };
    我不确定是否需要 APP_INITIALIZER 和 checkForUpdate,但这样我将延迟减少到 1-2 秒(而不是 5-10 秒甚至更多)

    关于javascript - Angular PWA 更新太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61042675/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com