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
浏览:796

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]删除
最新教程 更多>
  • 如何解决AppEngine中“无法猜测文件类型,使用application/octet-stream...”错误?
    如何解决AppEngine中“无法猜测文件类型,使用application/octet-stream...”错误?
    appEngine静态文件mime type override ,静态文件处理程序有时可以覆盖正确的mime类型,在错误消息中导致错误消息:“无法猜测mimeType for for file for file for [File]。 application/application/octet...
    编程 发布于2025-05-22
  • 如何在Java的全屏独家模式下处理用户输入?
    如何在Java的全屏独家模式下处理用户输入?
    Handling User Input in Full Screen Exclusive Mode in JavaIntroductionWhen running a Java application in full screen exclusive mode, the usual event ha...
    编程 发布于2025-05-22
  • Python读取CSV文件UnicodeDecodeError终极解决方法
    Python读取CSV文件UnicodeDecodeError终极解决方法
    在试图使用已内置的CSV模块读取Python中时,CSV文件中的Unicode Decode Decode Decode Decode decode Error读取,您可能会遇到错误的错误:无法解码字节 在位置2-3中:截断\ uxxxxxxxx逃脱当CSV文件包含特殊字符或Unicode的路径逃...
    编程 发布于2025-05-22
  • 找到最大计数时,如何解决mySQL中的“组函数\”错误的“无效使用”?
    找到最大计数时,如何解决mySQL中的“组函数\”错误的“无效使用”?
    如何在mySQL中使用mySql 检索最大计数,您可能会遇到一个问题,您可能会在尝试使用以下命令:理解错误正确找到由名称列分组的值的最大计数,请使用以下修改后的查询: 计数(*)为c 来自EMP1 按名称组 c desc订购 限制1 查询说明 select语句提取名称列和每个名称...
    编程 发布于2025-05-22
  • 如何使用Python的请求和假用户代理绕过网站块?
    如何使用Python的请求和假用户代理绕过网站块?
    如何使用Python的请求模拟浏览器行为,以及伪造的用户代理提供了一个用户 - 代理标头一个有效方法是提供有效的用户式header,以提供有效的用户 - 设置,该标题可以通过browser和Acterner Systems the equestersystermery和操作系统。通过模仿像Chro...
    编程 发布于2025-05-22
  • 在GO中构造SQL查询时,如何安全地加入文本和值?
    在GO中构造SQL查询时,如何安全地加入文本和值?
    在go中构造文本sql查询时,在go sql queries 中,在使用conting and contement和contement consem per时,尤其是在使用integer per当per当per时,per per per当per. [&​​&&&&&&&&&&&&&&&默元组方法在...
    编程 发布于2025-05-22
  • 大批
    大批
    [2 数组是对象,因此它们在JS中也具有方法。 切片(开始):在新数组中提取部分数组,而无需突变原始数组。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    编程 发布于2025-05-22
  • Python元类工作原理及类创建与定制
    Python元类工作原理及类创建与定制
    python中的metaclasses是什么? Metaclasses负责在Python中创建类对象。就像类创建实例一样,元类也创建类。他们提供了对类创建过程的控制层,允许自定义类行为和属性。在Python中理解类作为对象的概念,类是描述用于创建新实例或对象的蓝图的对象。这意味着类本身是使用类关...
    编程 发布于2025-05-22
  • 为什么尽管有效代码,为什么在PHP中捕获输入?
    为什么尽管有效代码,为什么在PHP中捕获输入?
    在php ;?>" method="post">The intention is to capture the input from the text box and display it when the submit button is clicked.但是,输出...
    编程 发布于2025-05-22
  • Spark DataFrame添加常量列的妙招
    Spark DataFrame添加常量列的妙招
    在Spark Dataframe 中创建一个常数列,可以通过多种方式实现具有适用于所有行的任意值的Spark DataFrame。使用文字值(SPARK 1.3)在尝试提供直接值时,用于此问题时,旨在为此目的的column方法可能会导致错误。 df.withcolumn('new_colu...
    编程 发布于2025-05-22
  • 如何克服PHP的功能重新定义限制?
    如何克服PHP的功能重新定义限制?
    克服PHP的函数重新定义限制在PHP中,多次定义一个相同名称的函数是一个no-no。尝试这样做,如提供的代码段所示,将导致可怕的“不能重新列出”错误。 但是,PHP工具腰带中有一个隐藏的宝石:runkit扩展。它使您能够灵活地重新定义函数。 runkit_function_renction_re...
    编程 发布于2025-05-22
  • 如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    如何修复\“常规错误:2006 MySQL Server在插入数据时已经消失\”?
    How to Resolve "General error: 2006 MySQL server has gone away" While Inserting RecordsIntroduction:Inserting data into a MySQL database can...
    编程 发布于2025-05-22
  • 为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    网格超过身体,用100%grid-template-columns 为什么在grid-template-colms中具有100%的显示器,当位置设置为设置的位置时,grid-template-colly修复了?问题: 考虑以下CSS和html: class =“ snippet-code”> g...
    编程 发布于2025-05-22
  • 如何使用FormData()处理多个文件上传?
    如何使用FormData()处理多个文件上传?
    )处理多个文件输入时,通常需要处理多个文件上传时,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    编程 发布于2025-05-22
  • 如何使用Python有效地以相反顺序读取大型文件?
    如何使用Python有效地以相反顺序读取大型文件?
    在python 中,如果您使用一个大文件,并且需要从最后一行读取其内容,则在第一行到第一行,Python的内置功能可能不合适。这是解决此任务的有效解决方案:反向行读取器生成器 == ord('\ n'): 缓冲区=缓冲区[:-1] ...
    编程 发布于2025-05-22

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

Copyright© 2022 湘ICP备2022001581号-3