将任何静态网站转换为 PWA 什么是 PWA? 1. 创建 manifest.json 文件 2. 添加 Service Worker 3. 注册 Service Worker 4. 使网站离线工作 免责声明:通过 Google 获取更多信息 希望你喜欢这篇文章

2025-06-10

将任何静态网站转换为 PWA

什么是 PWA?

1.创建 manifest.json 文件

2. 添加 Service Worker

3. 注册 Service Worker

4. 让网站离线工作

免责声明:

通过 Google 获取更多信息

希望你喜欢这篇文章

渐进式网页应用

什么是 PWA?

渐进式 Web 应用程序是一种具有 Web 覆盖范围的用户体验,并且:

可靠- 即使在网络条件不确定的情况下也能立即加载并且不会显示 downasaur。

快速- 通过流畅的动画快速响应用户交互,并且不会出现卡顿滚动。

引人入胜——感觉就像设备上的自然应用程序,具有身临其境的用户体验。

这种新的质量水平使得渐进式 Web 应用程序能够在用户的主屏幕上占有一席之地。

1.创建 manifest.json 文件

清单是一个简单的 JSON 文件,它向浏览器介绍您的 Web 应用,以及它在“安装”到用户的移动设备或桌面设备后应如何运行。Chrome 需要清单才能显示“添加到主屏幕”提示。

典型的清单文件包括有关应用程序名称、应使用的图标、启动时应启动的 start_url 等信息。

{
    "name": "K IRSHAD ALI",
    "short_name": "ALI",
    "icons": [
        {
            "src": "img/logo.png",
            "sizes": "92x92",
            "type": "image/png"
        },
        {
            "src": "/img/logo.png",
            "sizes": "144x144",
            "type": "image/png"
        },
        {
            "src": "img/logo.png",
            "sizes": "152x152",
            "type": "image/png"
        }        
    ],
    "start_url": "/",
    "display": "standalone",
    "orientation": "portrait",
    "background_color": "#f0f2f5",
    "theme_color": "#96f2d7"
}
Enter fullscreen mode Exit fullscreen mode

并将其连接到您的设备上index.html以便工作。

<link rel="manifest" href="manifest.json">

2. 添加 Service Worker

Service Worker 是浏​​览器在用户离开页面时可以运行的后台脚本。它提供离线支持,并在通知推送时激活。

创建 Service Worker(创建一个名为 SW.js 的文件),

复制此代码到SW.js

/** An empty service worker! */
self.addEventListener('fetch', function(event) {
});

就是这样。

3. 注册 Service Worker

您必须在您的网站代码中注册该代码,为此,请打开您的App.js文件并粘贴此代码,

navigator.serviceWorker &&
navigator.serviceWorker.register('SW.js').then(function (registration)
{
});

该代码将在每次页面加载时执行。请重新加载页面,然后检查 chrome://serviceworker-internals/ 是否正常工作。

现在,您的网站将能够提示用户在主屏幕上安装它,其次,您将能够使您的网站支持推送通知,甚至可以离线工作。

4. 让网站离线工作

第一步是打开 sw.js 脚本并获取缓存对象。获取缓存对象后,更新代码并将整个网站应用到缓存中。

现在就试试效果吧。卸载当前应用,并将其加载到 Chrome 浏览器。接下来,刷新页面,并在右上角菜单中选择“添加到主屏幕”。

为了遵循 Service Worker 更改时页面应重新加载并重新安装的规则,您只需添加一个包含 Service Worker 版本号的组件即可。当版本号发生更改时,安装操作将再次发生,并缓存可能已更改的资源。

恭喜,您现在知道如何将网站转变为渐进式 Web 应用程序,如果您按照这些步骤操作,您现在甚至已经将您的网站迁移到渐进式 Web 应用程序!

免责声明:

 While these steps will give you, the developer, an exact idea of how you will have to fill in the blanks and move from Point A in the process to Point C, if you are reading this as an enthusiastic entrepreneur who wishes to take charge of the migration, I would say, don’t do it without a person who excels in knowing how to turn website into progressive Web App.
Enter fullscreen mode Exit fullscreen mode

虽然这些步骤比较简单,但实际开发过程中,你还会遇到很多其他问题。所以,与其因为对字里行间的细节不了解而自己尝试这些步骤,最终得到不同的结果,不如把这项工作交给精通该领域的渐进式 Web 应用专家。

通过 Google 获取更多信息

https://developers.google.com/web/progressive-web-apps

希望你喜欢这篇文章

伊尔沙德·阿里

访问我:https://irshadali.site

鏂囩珷鏉ユ簮锛�https://dev.to/phonerefer/convert-any-static-website-to-pwa-3fkb
PREV
避免使用默认导出
NEXT
原始 JS 中的双向数据绑定(POC)