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
瀏覽:512

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如有侵犯,請聯絡study_golang @163.com刪除
最新教學 更多>
  • C++中如何將獨占指針作為函數或構造函數參數傳遞?
    C++中如何將獨占指針作為函數或構造函數參數傳遞?
    在構造函數和函數中將唯一的指數管理為參數 unique pointers( unique_ptr [2啟示。通過值: base(std :: simelor_ptr n) :next(std :: move(n)){} 此方法將唯一指針的所有權轉移到函數/對象。指針的內容被移至功能中,在操作...
    程式設計 發佈於2025-05-22
  • 如何檢查對像是否具有Python中的特定屬性?
    如何檢查對像是否具有Python中的特定屬性?
    方法來確定對象屬性存在尋求一種方法來驗證對像中特定屬性的存在。考慮以下示例,其中嘗試訪問不確定屬性會引起錯誤: >>> a = someClass() >>> A.property Trackback(最近的最新電話): 文件“ ”,第1行, AttributeError: SomeClass...
    程式設計 發佈於2025-05-22
  • 找到最大計數時,如何解決mySQL中的“組函數\”錯誤的“無效使用”?
    找到最大計數時,如何解決mySQL中的“組函數\”錯誤的“無效使用”?
    如何在mySQL中使用mySql 檢索最大計數,您可能會遇到一個問題,您可能會在嘗試使用以下命令:理解錯誤正確找到由名稱列分組的值的最大計數,請使用以下修改後的查詢: 計數(*)為c 來自EMP1 按名稱組 c desc訂購 限制1 查詢說明 select語句提取名稱列和每個名稱...
    程式設計 發佈於2025-05-22
  • 將圖片浮動到底部右側並環繞文字的技巧
    將圖片浮動到底部右側並環繞文字的技巧
    在Web設計中圍繞在Web設計中,有時可以將圖像浮動到頁面右下角,從而使文本圍繞它纏繞。這可以在有效地展示圖像的同時創建一個吸引人的視覺效果。 css位置在右下角,使用css float and clear properties: img { 浮點:對; ...
    程式設計 發佈於2025-05-22
  • 如何有效地轉換PHP中的時區?
    如何有效地轉換PHP中的時區?
    在PHP 利用dateTime對象和functions DateTime對象及其相應的功能別名為時區轉換提供方便的方法。例如: //定義用戶的時區 date_default_timezone_set('歐洲/倫敦'); //創建DateTime對象 $ dateTime = ne...
    程式設計 發佈於2025-05-22
  • 在C#中如何高效重複字符串字符用於縮進?
    在C#中如何高效重複字符串字符用於縮進?
    在基於項目的深度下固定字符串時,重複一個字符串以進行凹痕,很方便有效地有一種有效的方法來返回字符串重複指定的次數的字符串。使用指定的次數。 constructor 這將返回字符串“ -----”。 字符串凹痕= new String(' - ',depth); console.W...
    程式設計 發佈於2025-05-22
  • 解決Spring Security 4.1及以上版本CORS問題指南
    解決Spring Security 4.1及以上版本CORS問題指南
    彈簧安全性cors filter:故障排除常見問題 在將Spring Security集成到現有項目中時,您可能會遇到與CORS相關的錯誤,如果像“訪問Control-allo-allow-Origin”之類的標頭,則無法設置在響應中。為了解決此問題,您可以實現自定義過濾器,例如代碼段中的MyFi...
    程式設計 發佈於2025-05-22
  • 人臉檢測失敗原因及解決方案:Error -215
    人臉檢測失敗原因及解決方案:Error -215
    錯誤處理:解決“ error:( - 215)!empty()in Function openCv in Function MultSiscale中的“檢測”中的錯誤:在功能檢測中。”當Face Cascade分類器(即面部檢測至關重要的組件)未正確加載時,通常會出現此錯誤。 要解決此問題,必...
    程式設計 發佈於2025-05-22
  • 在程序退出之前,我需要在C ++中明確刪除堆的堆分配嗎?
    在程序退出之前,我需要在C ++中明確刪除堆的堆分配嗎?
    在C中的顯式刪除 在C中的動態內存分配時,開發人員通常會想知道是否有必要在heap-procal extrable exit exit上進行手動調用“ delete”操作員,但開發人員通常會想知道是否需要手動調用“ delete”操作員。本文深入研究了這個主題。 在C主函數中,使用了動態分配變量(...
    程式設計 發佈於2025-05-22
  • 如何將MySQL數據庫添加到Visual Studio 2012中的數據源對話框中?
    如何將MySQL數據庫添加到Visual Studio 2012中的數據源對話框中?
    在Visual Studio 2012 儘管已安裝了MySQL Connector v.6.5.4,但無法將MySQL數據庫添加到實體框架的“ DataSource對話框”中。為了解決這一問題,至關重要的是要了解MySQL連接器v.6.5.5及以後的6.6.x版本將提供MySQL的官方Visual...
    程式設計 發佈於2025-05-22
  • 如何在Chrome中居中選擇框文本?
    如何在Chrome中居中選擇框文本?
    選擇框的文本對齊:局部chrome-inly-ly-ly-lyly solument 您可能希望將文本中心集中在選擇框中,以獲取優化的原因或提高可訪問性。但是,在CSS中的選擇元素中手動添加一個文本 - 對屬性可能無法正常工作。 初始嘗試 state)</option> < o...
    程式設計 發佈於2025-05-22
  • 在Oracle SQL中如何提取下劃線前的子字符串?
    在Oracle SQL中如何提取下劃線前的子字符串?
    [ 在oracle sql 解決方案: Explanation:SUBSTR function extracts a substring starting from the specified position (0) and continuing for a specified length.IN...
    程式設計 發佈於2025-05-22
  • 使用jQuery如何有效修改":after"偽元素的CSS屬性?
    使用jQuery如何有效修改":after"偽元素的CSS屬性?
    在jquery中了解偽元素的限制:訪問“ selector 嘗試修改“:”選擇器的CSS屬性時,您可能會遇到困難。 This is because pseudo-elements are not part of the DOM (Document Object Model) and are th...
    程式設計 發佈於2025-05-22
  • 為什麼PYTZ最初顯示出意外的時區偏移?
    為什麼PYTZ最初顯示出意外的時區偏移?
    與pytz 最初從pytz獲得特定的偏移。例如,亞洲/hong_kong最初顯示一個七個小時37分鐘的偏移: 差異源利用本地化將時區分配給日期,使用了適當的時區名稱和偏移量。但是,直接使用DateTime構造器分配時區不允許進行正確的調整。 example pytz.timezone(&#...
    程式設計 發佈於2025-05-22

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3