This simple PWA can run across all platforms, leveraging the web’s ubiquity.

  1. Improved Performance

Performance is a critical factor for any web-based application. Progressive Web Apps improve load times by caching assets and content using service workers, allowing users to quickly access previously visited pages, even with poor internet connections.

Example: Service Worker for Caching

A service worker is a script that the browser runs in the background, enabling features like caching, push notifications, and background sync. Here’s an example of a service worker that caches static assets:

const CACHE_NAME = \\'v1_cache\\';const urlsToCache = [    \\'/\\',    \\'/styles.css\\',    \\'/script.js\\',    \\'/offline.html\\'];// Install the service workerself.addEventListener(\\'install\\', event => {    event.waitUntil(        caches.open(CACHE_NAME)            .then(cache => {                return cache.addAll(urlsToCache);            })    );});// Fetch and serve cached assetsself.addEventListener(\\'fetch\\', event => {    event.respondWith(        caches.match(event.request)            .then(response => {                return response || fetch(event.request);            })            .catch(() => caches.match(\\'/offline.html\\'))    );});

With this setup, the PWA will load instantly for returning users and display a custom offline page when there is no internet connectivity.

  1. Offline Functionality

PWAs offer offline functionality, ensuring users can continue interacting with the app when they have no internet access. By caching essential resources using service workers, the app can serve previously loaded content and even queue actions for later synchronization.

Example: Offline Handling with Service Worker

Let’s extend our service worker to handle offline scenarios effectively:

self.addEventListener(\\'fetch\\', event => {    event.respondWith(        fetch(event.request)            .catch(() => {                return caches.match(event.request).then(response => {                    return response || caches.match(\\'/offline.html\\');                });            })    );});

This code ensures that if a user loses connectivity, they can still access the cached version of the app or an offline page.

  1. Better User Engagement with Push Notifications

PWAs allow developers to engage users through push notifications, even when the app is not actively running in the foreground. Push notifications help keep users informed about updates, reminders, and other interactions that can boost engagement.

Example: Push Notifications

First, we need to ask for permission from the user to send notifications:

Notification.requestPermission().then(permission => {    if (permission === \\'granted\\') {        navigator.serviceWorker.getRegistration().then(registration => {            registration.showNotification(\\'Hello, PWA User!\\', {                body: \\'Thanks for using our Progressive Web App.\\',                icon: \\'/images/icon.png\\'            });        });    }});

This code will display a notification to the user if they grant permission. Push notifications make your PWA more engaging by reminding users to revisit the app.

  1. Reduced Development Costs

Developing separate native apps for iOS, Android, and web platforms is expensive. PWAs solve this by using a single codebase across all platforms. By building one Progressive Web App, you can drastically reduce the development time and costs associated with maintaining multiple apps.

Example: Unified Codebase

// This single piece of code works on both mobile and desktop environmentsfunction detectDevice() {    if (window.innerWidth < 768) {        return \\'Mobile\\';    } else {        return \\'Desktop\\';    }}console.log(`You are using a ${detectDevice()} device`);

With such cross-platform compatibility, businesses can save on development and maintenance costs while ensuring a consistent user experience.

  1. Increased Security

Since PWAs are served via HTTPS, they inherently ensure that all communications between the user and the server are encrypted, preventing man-in-the-middle attacks. Additionally, the use of service workers ensures that only the content that is cached is displayed to users, preventing malicious injections.

Example: Enforcing HTTPS

Make sure your web server enforces HTTPS:

# Redirect all HTTP traffic to HTTPSRewriteEngine OnRewriteCond %{HTTPS} offRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This simple configuration makes sure that any non-secure HTTP requests are redirected to HTTPS, increasing security for your Progressive Web App.

  1. Discoverability Through Search Engines

Unlike native apps, which are primarily distributed through app stores, PWAs are discoverable through search engines like regular websites. This makes them easily accessible to users and allows businesses to take advantage of SEO techniques to increase visibility.

Example: SEO Optimization in PWA

Use meta tags and structured data to optimize your PWA for search engines:

By optimizing your PWA for SEO, you improve its chances of being found by users searching for relevant topics.

  1. Native App-Like Experience

PWAs provide a native app-like experience by offering features such as offline access, home screen installation, push notifications, and a responsive design. This provides users with the benefits of a native app without requiring a download from an app store.

Example: Adding PWA to Home Screen

Here’s how you can allow users to add your PWA to their home screen on mobile devices:

let deferredPrompt;window.addEventListener(\\'beforeinstallprompt\\', event => {    // Prevent the mini-infobar from appearing on mobile    event.preventDefault();    deferredPrompt = event;    // Display your custom install button    document.getElementById(\\'install-button\\').style.display = \\'block\\';    document.getElementById(\\'install-button\\').addEventListener(\\'click\\', () => {        deferredPrompt.prompt();        deferredPrompt.userChoice.then(choiceResult => {            if (choiceResult.outcome === \\'accepted\\') {                console.log(\\'User accepted the PWA installation\\');            } else {                console.log(\\'User dismissed the PWA installation\\');            }            deferredPrompt = null;        });    });});

With this code, users can add the app to their home screen, giving it the appearance and feel of a native app.

  1. Automatic Updates

Progressive Web Apps update automatically in the background, ensuring that users always have the latest version. There’s no need for users to manually download updates, as PWAs automatically fetch the latest files when they become available.

Example: Force Update in PWA

You can force an update for users when a new version of your service worker is available:

self.addEventListener(\\'install\\', event => {    event.waitUntil(        caches.open(CACHE_NAME).then(cache => {            return cache.addAll(urlsToCache);        }).then(() => {            self.skipWaiting();        })    );});self.addEventListener(\\'activate\\', event => {    event.waitUntil(        caches.keys().then(cacheNames => {            return Promise.all(                cacheNames.map(cache => {                    if (cache !== CACHE_NAME) {                        return caches.delete(cache);                    }                })            );        })    );});

This ensures that users get the latest version of your PWA without needing to take any manual action.

  1. Reduced Data Consumption

Compared to traditional websites or native apps, PWAs consume far less data, which is especially important for users in areas with limited or expensive data plans. By caching content locally, PWAs minimize data usage and reduce the load on servers.

Example: Minimal Data Consumption

with Lazy Loading

Implementing lazy loading allows your PWA to load images and content only when they are needed, reducing data usage:

\\\"发现渐进式document.addEventListener(\\'DOMContentLoaded\\', function() {    let lazyImages = [].slice.call(document.querySelectorAll(\\'img.lazy\\'));    if (\\'IntersectionObserver\\' in window) {        let lazyImageObserver = new IntersectionObserver(function(entries, observer) {            entries.forEach(function(entry) {                if (entry.isIntersecting) {                    let lazyImage = entry.target;                    lazyImage.src = lazyImage.dataset.src;                    lazyImage.classList.remove(\\'lazy\\');                    lazyImageObserver.unobserve(lazyImage);                }            });        });        lazyImages.forEach(function(lazyImage) {            lazyImageObserver.observe(lazyImage);        });    }});

This reduces bandwidth by loading content only when it is needed, improving both performance and user experience.

Conclusion

Progressive Web Apps (PWAs) are the future of web development, offering cross-platform compatibility, offline functionality, enhanced performance, and better user engagement. Whether you’re looking to reduce development costs, improve security, or offer users a native app-like experience, PWAs are an excellent choice for your next project.

With features like automatic updates, push notifications, and offline capabilities, PWAs provide a seamless and efficient user experience across all devices. As businesses continue to explore ways to improve their digital presence, the adoption of Progressive Web Apps is bound to rise.

References:

Google Developers - Introduction to Progressive Web Apps

Mozilla Developer Network - Service Workers

W3C - Web App Manifest

","image":"http://www.luping.net/uploads/20241117/17318257286739904076217.jpg","datePublished":"2024-11-17T15:40:34+08:00","dateModified":"2024-11-17T15:40:34+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 发现渐进式 Web 应用程序为您的下一个项目带来的最大优势

发现渐进式 Web 应用程序为您的下一个项目带来的最大优势

发布于2024-11-17
浏览:964

Discover the Top Advantages of Progressive Web Apps for Your Next Project

Progressive online Apps, or PWAs, are quickly changing the online development landscape. PWAs are becoming the ideal way to connect mobile applications and traditional websites as companies look for ways to increase efficiency, save expenses, and provide consistent user experiences across all platforms. In-depth code examples are provided to illustrate the characteristics and advantages of Progressive Web Apps, which are explored in this article along with the top 10 reasons to use them for your next project.

  1. Cross-Platform Compatibility

Progressive Web Apps' cross-platform interoperability is one of the strongest arguments in favor of using them. Desktop, smartphone, or tablet computers that have an up-to-date web browser can all use PWAs. Without the need for different codebases for the desktop, iOS, and Android environments, this flexibility guarantees that your product reaches a wider audience.

With PWAs, you write the app once using standard web technologies such as HTML, CSS, and JavaScript, and it works seamlessly across devices.

Example: Basic PWA Setup

Here’s how you can create a basic Progressive Web App structure using HTML, JavaScript, and a service worker:



    My First PWA

Hello, PWA World!

This simple PWA can run across all platforms, leveraging the web’s ubiquity.

  1. Improved Performance

Performance is a critical factor for any web-based application. Progressive Web Apps improve load times by caching assets and content using service workers, allowing users to quickly access previously visited pages, even with poor internet connections.

Example: Service Worker for Caching

A service worker is a script that the browser runs in the background, enabling features like caching, push notifications, and background sync. Here’s an example of a service worker that caches static assets:

const CACHE_NAME = 'v1_cache';
const urlsToCache = [
    '/',
    '/styles.css',
    '/script.js',
    '/offline.html'
];

// Install the service worker
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => {
                return cache.addAll(urlsToCache);
            })
    );
});

// Fetch and serve cached assets
self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => {
                return response || fetch(event.request);
            })
            .catch(() => caches.match('/offline.html'))
    );
});

With this setup, the PWA will load instantly for returning users and display a custom offline page when there is no internet connectivity.

  1. Offline Functionality

PWAs offer offline functionality, ensuring users can continue interacting with the app when they have no internet access. By caching essential resources using service workers, the app can serve previously loaded content and even queue actions for later synchronization.

Example: Offline Handling with Service Worker

Let’s extend our service worker to handle offline scenarios effectively:

self.addEventListener('fetch', event => {
    event.respondWith(
        fetch(event.request)
            .catch(() => {
                return caches.match(event.request).then(response => {
                    return response || caches.match('/offline.html');
                });
            })
    );
});

This code ensures that if a user loses connectivity, they can still access the cached version of the app or an offline page.

  1. Better User Engagement with Push Notifications

PWAs allow developers to engage users through push notifications, even when the app is not actively running in the foreground. Push notifications help keep users informed about updates, reminders, and other interactions that can boost engagement.

Example: Push Notifications

First, we need to ask for permission from the user to send notifications:

Notification.requestPermission().then(permission => {
    if (permission === 'granted') {
        navigator.serviceWorker.getRegistration().then(registration => {
            registration.showNotification('Hello, PWA User!', {
                body: 'Thanks for using our Progressive Web App.',
                icon: '/images/icon.png'
            });
        });
    }
});

This code will display a notification to the user if they grant permission. Push notifications make your PWA more engaging by reminding users to revisit the app.

  1. Reduced Development Costs

Developing separate native apps for iOS, Android, and web platforms is expensive. PWAs solve this by using a single codebase across all platforms. By building one Progressive Web App, you can drastically reduce the development time and costs associated with maintaining multiple apps.

Example: Unified Codebase

// This single piece of code works on both mobile and desktop environments
function detectDevice() {
    if (window.innerWidth 



With such cross-platform compatibility, businesses can save on development and maintenance costs while ensuring a consistent user experience.

  1. Increased Security

Since PWAs are served via HTTPS, they inherently ensure that all communications between the user and the server are encrypted, preventing man-in-the-middle attacks. Additionally, the use of service workers ensures that only the content that is cached is displayed to users, preventing malicious injections.

Example: Enforcing HTTPS

Make sure your web server enforces HTTPS:

# Redirect all HTTP traffic to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This simple configuration makes sure that any non-secure HTTP requests are redirected to HTTPS, increasing security for your Progressive Web App.

  1. Discoverability Through Search Engines

Unlike native apps, which are primarily distributed through app stores, PWAs are discoverable through search engines like regular websites. This makes them easily accessible to users and allows businesses to take advantage of SEO techniques to increase visibility.

Example: SEO Optimization in PWA

Use meta tags and structured data to optimize your PWA for search engines:

By optimizing your PWA for SEO, you improve its chances of being found by users searching for relevant topics.

  1. Native App-Like Experience

PWAs provide a native app-like experience by offering features such as offline access, home screen installation, push notifications, and a responsive design. This provides users with the benefits of a native app without requiring a download from an app store.

Example: Adding PWA to Home Screen

Here’s how you can allow users to add your PWA to their home screen on mobile devices:

let deferredPrompt;
window.addEventListener('beforeinstallprompt', event => {
    // Prevent the mini-infobar from appearing on mobile
    event.preventDefault();
    deferredPrompt = event;
    // Display your custom install button
    document.getElementById('install-button').style.display = 'block';

    document.getElementById('install-button').addEventListener('click', () => {
        deferredPrompt.prompt();
        deferredPrompt.userChoice.then(choiceResult => {
            if (choiceResult.outcome === 'accepted') {
                console.log('User accepted the PWA installation');
            } else {
                console.log('User dismissed the PWA installation');
            }
            deferredPrompt = null;
        });
    });
});

With this code, users can add the app to their home screen, giving it the appearance and feel of a native app.

  1. Automatic Updates

Progressive Web Apps update automatically in the background, ensuring that users always have the latest version. There’s no need for users to manually download updates, as PWAs automatically fetch the latest files when they become available.

Example: Force Update in PWA

You can force an update for users when a new version of your service worker is available:

self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME).then(cache => {
            return cache.addAll(urlsToCache);
        }).then(() => {
            self.skipWaiting();
        })
    );
});

self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames.map(cache => {
                    if (cache !== CACHE_NAME) {
                        return caches.delete(cache);
                    }
                })
            );
        })
    );
});

This ensures that users get the latest version of your PWA without needing to take any manual action.

  1. Reduced Data Consumption

Compared to traditional websites or native apps, PWAs consume far less data, which is especially important for users in areas with limited or expensive data plans. By caching content locally, PWAs minimize data usage and reduce the load on servers.

Example: Minimal Data Consumption

with Lazy Loading

Implementing lazy loading allows your PWA to load images and content only when they are needed, reducing data usage:

发现渐进式 Web 应用程序为您的下一个项目带来的最大优势

document.addEventListener('DOMContentLoaded', function() {
    let lazyImages = [].slice.call(document.querySelectorAll('img.lazy'));

    if ('IntersectionObserver' in window) {
        let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    let lazyImage = entry.target;
                    lazyImage.src = lazyImage.dataset.src;
                    lazyImage.classList.remove('lazy');
                    lazyImageObserver.unobserve(lazyImage);
                }
            });
        });

        lazyImages.forEach(function(lazyImage) {
            lazyImageObserver.observe(lazyImage);
        });
    }
});

This reduces bandwidth by loading content only when it is needed, improving both performance and user experience.

Conclusion

Progressive Web Apps (PWAs) are the future of web development, offering cross-platform compatibility, offline functionality, enhanced performance, and better user engagement. Whether you’re looking to reduce development costs, improve security, or offer users a native app-like experience, PWAs are an excellent choice for your next project.

With features like automatic updates, push notifications, and offline capabilities, PWAs provide a seamless and efficient user experience across all devices. As businesses continue to explore ways to improve their digital presence, the adoption of Progressive Web Apps is bound to rise.

References:

Google Developers - Introduction to Progressive Web Apps

Mozilla Developer Network - Service Workers

W3C - Web App Manifest

版本声明 本文转载于:https://dev.to/nilebits/discover-the-top-10-advantages-of-progressive-web-apps-for-your-next-project-pmc?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    如何在 PHP 中组合两个关联数组,同时保留唯一 ID 并处理重复名称?
    在 PHP 中组合关联数组在 PHP 中,将两个关联数组组合成一个数组是一项常见任务。考虑以下请求:问题描述:提供的代码定义了两个关联数组,$array1 和 $array2。目标是创建一个新数组 $array3,它合并两个数组中的所有键值对。 此外,提供的数组具有唯一的 ID,而名称可能重合。要求...
    编程 发布于2024-11-17
  • 大批
    大批
    方法是可以在对象上调用的 fns 数组是对象,因此它们在 JS 中也有方法。 slice(begin):将数组的一部分提取到新数组中,而不改变原始数组。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index p...
    编程 发布于2024-11-17
  • 如何在 Keras 中实现自己的损失函数?
    如何在 Keras 中实现自己的损失函数?
    Keras 中的自定义损失函数实现在 Keras 中,可以实现自定义损失函数来满足特定的训练要求。其中一个函数是骰子误差系数,它测量真实标签和预测标签之间的重叠。要在 Keras 中创建自定义损失函数,请按照以下步骤操作:1。实现系数函数骰子误差系数可以写为:dice coefficient = (...
    编程 发布于2024-11-17
  • Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta 中的列偏移发生了什么?
    Bootstrap 4 Beta:列偏移的删除和恢复Bootstrap 4 在其 Beta 1 版本中引入了重大更改柱子偏移了。然而,随着 Beta 2 的后续发布,这些变化已经逆转。从 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    编程 发布于2024-11-17
  • Go如何在没有传统机制的情况下实现多态?
    Go如何在没有传统机制的情况下实现多态?
    探索Go语言中的多态性在面向对象编程中,多态性允许对象根据其类表现出不同的行为。但在Go中,多态性的概念并不是传统意义上的实现。让我们深入探究一下这背后的原因,探讨如何在 Go 中实现类似的功能。为什么 Go 缺乏传统的多态性Go 不是传统的面向对象语言。它采用了不同的方法,使用:组合:由其他对象或...
    编程 发布于2024-11-17
  • 如何在Java中正确通过套接字传输文件?
    如何在Java中正确通过套接字传输文件?
    Java 通过套接字传输文件:发送和接收字节数组在 Java 中,通过套接字传输文件涉及将文件转换为字节数组,通过套接字发送它们,然后在接收端将字节转换回文件。本文解决了 Java 开发人员在实现此文件传输功能时遇到的问题。服务器端问题服务器代码在接收时似乎创建了一个空文件来自客户端的数据。为了解决...
    编程 发布于2024-11-17
  • 如何在 JavaScript 中格式化数字以显示最少的小数位数?
    如何在 JavaScript 中格式化数字以显示最少的小数位数?
    在 JavaScript 中格式化数字关于在 JavaScript 中格式化数字的查询,您可以利用内置函数 toLocaleString() 和minimumFractionDigits 选项。toLocaleString() 方法使您能够根据用户的区域设置或指定的区域设置数字格式语言环境。通过将m...
    编程 发布于2024-11-17
  • 如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    如何修复 macOS 上 Django 中的“配置不正确:加载 MySQLdb 模块时出错”?
    MySQL配置不正确:相对路径的问题在Django中运行python manage.py runserver时,可能会遇到以下错误:ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-...
    编程 发布于2024-11-17
  • 如何在 Go 中将数字转换为字母?
    如何在 Go 中将数字转换为字母?
    在 Go 中将数字转换为字母了解了将数字转换为字母的需要,让我们探索在 Go 中实现这一目标的各种方法.数字到符文的转换一种简单的方法是将数字添加到常量 'A' - 1,其中每个数字相加代表字母表中的一个字母。例如,加 1 得到“A”,加 2 得到“B”。func toChar(i ...
    编程 发布于2024-11-17
  • 如何在 PHP 中提取不带扩展名的文件名?
    如何在 PHP 中提取不带扩展名的文件名?
    在 PHP 中提取不带扩展名的文件名使用神奇常量 __FILE__ 可以轻松获取 PHP 中当前执行脚本的文件名。但是,如果您需要提取不带扩展名的文件名,例如“.php”后缀,则过程略有不同。basename() 解决方案:要使用basename()函数删除扩展名,您可以:basename(__FI...
    编程 发布于2024-11-17
  • 如何在 PHP 和 MySQL 中同步时区?
    如何在 PHP 和 MySQL 中同步时区?
    在 PHP 和 MySQL 中同步时区您正在开发一个需要使用 PHP date() 函数在 MySQL 中存储日期的应用程序。有必要使用 NOW() 在 MySQL 中比较这些日期来计算时间差异。但是,PHP date() 函数使用 PHP 中定义的时区,而 NOW() 使用 MySQL 服务器中配...
    编程 发布于2024-11-17
  • 如何使用准备好的语句在 PHP MySQLi 中准备安全更新查询?
    如何使用准备好的语句在 PHP MySQLi 中准备安全更新查询?
    如何为更新查询准备语句为了增强使用 PHP MySQLi 查询更新数据库时的数据安全性,建议采用准备好的声明。虽然 PHP 文档提供了有关 bind_param() 的信息,但它缺少特定于更新查询的示例。让我们深入研究如何为更新查询制定准备好的语句:准备查询语句:将更新查询中的所有变量替换为问号:$...
    编程 发布于2024-11-17
  • 如何将文本保留在圆角 Div 内?
    如何将文本保留在圆角 Div 内?
    确保文本保留在圆角 Div 内在创建具有引人入胜的视觉元素的网页时,通常会遇到圆角的需求无缝集成文本内容的 div。然而,默认情况下,圆形 div 内的文本往往表现为其容器是方形的,超出了指定的圆形边界。为了解决此问题,存在多种解决方案,每种解决方案都有自己的优点和优势限制:1。 Shape-Out...
    编程 发布于2024-11-17
  • **扩展语法与其余参数:ES2015 中的区别是什么?**
    **扩展语法与其余参数:ES2015 中的区别是什么?**
    扩展语法和剩余参数:揭开 ES2015 中的差异浏览 ES2015 中扩展语法和剩余参数的细微差别可能是一个想法-令人难以置信的努力。在本指南中,我们将剖析它们在 JavaScript 不断发展的格局中的对比角色。理解扩展语法:从一到多扩展语法(用 ' 表示) ...')允许我们将可...
    编程 发布于2024-11-17
  • 为什么我的 Tomcat 服务器显示“所需的几个端口已在使用中”?
    为什么我的 Tomcat 服务器显示“所需的几个端口已在使用中”?
    Tomcat 服务器端口冲突:解决错误“Several Ports required are Already in Use”尝试在 Tomcat 上启动 JSP 程序时Eclipse 中,用户可能会遇到错误,指出 Tomcat 所需的多个端口已在使用中。出现此问题的原因是存在另一个 Tomcat 实...
    编程 发布于2024-11-17

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3