Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Progressive Web Application Development by Example
Progressive Web Application Development by Example

Progressive Web Application Development by Example: Develop fast, reliable, and engaging user experiences for the web

eBook
£17.99 £26.99
Paperback
£32.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Progressive Web Application Development by Example

Introduction to Progressive Web Apps

Over 80% of 328 million active Twitter users are mobile. Twitter knew they needed their mobile experience to be faster, more reliable, and engaging. They chose to launch their default mobile experience as a Progressive Web Application (PWA) in April 2017, called Twitter Lite.

Their goals were simple, faster load times, more engagement, and lower data consumption. They were able to achieve all three when comparing general activities to the non progressive web app version:

  • 65% increase in pages per session
  • 75% increase in Tweets sent
  • 20% decrease in bounce rate
"Twitter Lite is now the fastest, least expensive, and most reliable way to use Twitter. The web app rivals the performance of our native apps but requires less than 3% of the device storage space compared to Twitter for Android."
— Nicolas Gallagher, the Engineering Lead for Twitter Lite

This is just one example of online companies reaping the rewards that PWA offers. This book should serve as a starting point to arm you with the basic knowledge and confidence to create your first PWA.

In this book, you are going to learn how to build a PWA which will be ready for production use. In case you haven't created a PWA yet, you will learn how to make a simple PWA in the first part of this chapter.

This chapter will cover PWA fundamentals and the advantages they offer over classic websites and native applications. You will also see how to upgrade an existing 2048 game web application to a PWA. You will learn how to add a web manifest and service worker to the application, enabling PWA features using a localhost web server.

The purpose of this chapter is to get a general idea of how PWAs work, why you want to deliver PWAs, and to give you the skills to easily create PWAs with basic functionalities.

This chapter will cover the following points:

  • The purpose of PWA
  • PWA advantages
  • The basic technical requirements of a PWA
  • The three primary user experience PWA goals
  • How to upgrade an existing website and run it locally

The web as we know it is entering its third decade of existence. Over this time, the web has gone through many changes and enhancements. While the web possesses some great superpowers, it also had its limitations that inhibited it from delivering an experience in parity with native counterparts.

PWAs are a way to apply native browser technology to create web solutions that consumers want to add to their homescreen. Meanwhile, new web APIs are progressing to fill additional gaps in functionality between web and native apps.

The great thing about a PWA is existing websites can easily be upgraded to claim the PWA status. This can unlock new features in browsers and platforms to level up any website.

About a decade ago, not only was the web disrupted, but so was desktop computing when Apple released the iPhone. This ushered in a new era of mobile first computing. That era's web technology was not prepared for this rapid shift from desktops to handheld devices.

Changing to a mobile first world requires more than just responsive design techniques; it requires a new set of native APIs, capabilities, and coding techniques. The HTML, CSS, and JavaScript specifications and browsers have evolved over the past decade, catching up to the consumer expectations of client applications.

Today, we have a very rich set of native APIs and browsers, enabling everything from geo-location to voice input and camera manipulation. There are client platforms designed to provide a rich, mobile first canvas for developers to paint engaging user experiences.

In addition to great native APIs, browsers have added new features in service workers, web manifestations, and have begun requiring HTTPS to enable modern APIs. These three technical features are the core requirements to become a PWA. However, there is much more to the art of making a good PWA. This art requires a different approach to web development.

In this book, we are going to explore the requirements of a good PWA, and how to create new and upgrade existing websites as PWAs. Along the way, we will learn how to leverage new features such as IndexedDB, multi-media, and the Fetch API to add value to our applications.

As this book progresses, you will learn how to use service workers for caching, push notifications, and background synchronization. The next chapter delves into the web manifest file. Chapter 3, Making Your Website Secure, covers the subtleties of upgrading to HTTPS.

This book breaks down technical and experiential requirements so that you can create a good, PWA and demonstrates this with three sample applications:

  • The first application is a simple game, 2048. 2048 was very popular about three years ago and I still find it very addictive. Even though it's a simple game, it will demonstrate how the web can compete on an even level with common native applications.
  • Next, we will create a photo gallery website and see how to use service worker caching to create an application that loads instantly and runs with or without a network. The application will be comparable to many popular podcast players like iTunes and Stitcher.
  • The final application is a consumer event ticket application. This application will demonstrate advanced service worker techniques like cache invalidation. I will also cover tools you can use to validate your applications and help you scaffold them for quality and consistency.

All source code is available on GitHub, with links provided in this book. You're welcome to clone and fork these repositories. Make local copies and modify them as you wish. I would love to see how you enhance the demo applications.

Why we needed a new way to build websites

When Apple released the iPhone in 2007, they initially intended that applications to be built using HTML. They provided an initial platform to create web applications. However, Mac developers cried put for a better native application solution and Apple answered. Apple did so with the caveat of taking 30% of the application's revenue and controlling the applications that were distributed through a closed App Store.

The closed App Store violates the openness of the web by introducing a third-party gatekeeper. This creates a layer of delay as Apple reviews your application. The review process can result in your application being censored or denied entry. The one advantage App Store offers is a sense of security and trustworthiness for consumers.

To make the App Store model interesting for Apple, they decided to take a big cut for tax-native applications. In return, Apple handles all payment and distribution infrastructure for applications. However, the web has not had a problem collecting money from consumers, nor a distribution issue.

Credit card merchant accounts typically take 2% to 3% of a transaction. Hosting has become a cheap commodity, often costing $10 or less a month for most websites.

The next perceived problem the web has suffered from is performance. Performance issues are amplified on mobile devices. Smartphones and tablets have underpowered CPUs compared to their desktop counterparts. And while more mobile devices use WiFi, cellular connections, even in the developed world, are still unreliable.

When the iPhone was first released, the web was still very static compared to what we experience today. Up to that point, the web was not a platform with animations and dynamic content.

Over the last decade, rich user experiences have become commonplace on the web with the rise of single page applications and many large frameworks. These changes have been driven in large part due to the user experiences consumers have come to expect from many native applications.

Many developers have tried to hack their way to mimicking native application experiences on mobile devices. This has led to some good progress as well as some bad experiences and coding practices.

Most bad experiences are due to a lack of awareness of the available APIs and how to use them. Poor coding techniques have also created more issues than perceived value.

A common mistake I have seen a lot is the application of server-side architecture in the browser. While outside the scope of this book, it is important to note that for a good modern web user experience, you may have to let go of preconceived notions of how to develop websites.

A prime example of misunderstanding how to use the web platform and the capability gap can be demonstrated by an interview in 2012 with Mark Zuckerberg, at a Tech Crunch event. You can check out the following link for the article: http://tcrn.ch/2hwN6HF

Facebook tried to make the web its primary platform, but due to many engineering mistakes and browser/hardware limitations, they failed. At that point, they switched to native apps as a primary focus and have since created a very large, walled off community of data and interactions.

As you will see later in this book, Facebook dominates the mobile native application space. This leaves very little room for anybody else to gain screen time.

This is where PWAs can empower businesses and organizations to engage with consumers at a deeper level. This book is designed to give you the tools and knowledge to create PWAs to reach consumers for less money and effort. The web possesses several superpowers that native applications can't touch. Now, with emerging native APIs, the web surpasses native applications.

Real-world PWA examples

Flipkart, the Amazon of the Indian sub-continent, embraced PWA as soon as the term was first mentioned. In many ways, they are the poster child of doing a PWA the right way.

Flipkart's consumer market consists of customers almost entirely on poor mobile connections. Their mobile devices have limited storage and may or may not have a reliable 3G connection. In fact, 63% reach the site via 2G. A client application experience that loads quickly and works even when the network is absent gives Flipkart a business advantage.

The Flipkart PWA (https://developers.google.com/web/showcase/2016/flipkart) was created by a small team of engineers in 42 days, a small investment on their part that has paid huge dividends by increasing conversions by 70%. These are just some of their published key performance indicators:

  • Users time on the site with Flipkart lite vs previous mobile experience, 3.5 minutes vs 70 seconds
  • 3x more time spent on site
  • 40% higher re-engagement rate
  • 70% greater conversion rate among those arriving via the Add to Homescreen feature
  • 3x lower data usage

Over 50% of the Weather Channel's mobile usage comes from the web. Reaching consumers around the world is a priority. The web offers a reliable channel to reach everyone, which often means lower powered devices. Re-engagement and the delivery of timely information, such as storm warnings, was also very important.

The Weather Channel (https://developers.google.com/web/showcase/2016/weather-channel) created a PWA, implementing push notifications to deliver experiences matching their native application. This upgrade enabled their team to reach 178 countries and deliver weather forecasts while improving their load time:

  • This PWA is now available in 62 languages and 178 countries
  • 80% improvement in load time
  • Based on this successful global test, the team will expand the PWA to its U.S site in 2017

Lancôme (https://developers.google.com/web/showcase/2017/lancome) rebuilt their mobile web presence as a PWA and increased conversions by 17%. As they tracked mobile web usage, passing desktop, Lancôme saw their conversions drop. After considering a native application, they decided investing in the web was the right way to go.

They determined customers were not likely to download a native application, nor use it often. They knew a web presence would have to be done right, as doing so could generate more rewards. They decided to rebuild their web presence from the ground up as a PWA.

Overall benefits:

  • 84% decrease in time until the page is interactive
  • 17% increase in conversions
  • 15% decrease in bounce rate
  • 51% increase in mobile sessions

iOS improvements:

  • 53% increase in mobile sessions on iOS
  • 10% decrease in bounce rates on iOS

Push notification benefits:

  • 8% of consumers who tap on a push notification make a purchase
  • 18% open rate from push notifications
  • 12% increase in conversion rates on recovered carts via push notifications

If you are worried about browsers that do not support PWA technology yet, take note of the iOS statistics. Lancôme is not alone; almost every company embracing PWAs have reported similar improvements on iOS. Later, you will see how to polyfill caching and the Add to Homescreen experience in your applications to achieve similar results.

These are just a few samples of major brands that have adopted PWAs and reported benefits. There are many more smaller businesses also improving because they are building web experiences customers want to use. The great thing is you can start enhancing your existing web site today using examples from this chapter.

What are PWAs?

Two years ago, a Google Chrome engineer, Alex Russell, published the landmark blog post defining PWA. You can check the post on the following link: http://bit.ly/2n1vQ2r

With this blog post Alex declared that web could now stand toe to toe with native applications. But it goes beyond just native capabilities being added via service workers, and the Add to Homescreen heuristic also matters when it comes to building a website.

Another Google Chrome engineer, Chris Wilson said that Progressive Web Applications are a new level of thinking about the quality of your user experience.

What the Chrome team and other browsers want you to understand is that user experience is the most important part of your website or application. Browsers are providing you with the foundation to build great applications, but it is still up to you to make these experiences come to life.

I tend to think that there is a confidence issue web developers have compared to native application developers. There is still this perception that native rules everything. However, this is not really true. As we'll see later, there are far more accessible web pages than native applications., and there is much more room to grow your website's brand compared to a native application.

Native applications serve a purpose, and that purpose is starting to fade away. The former head of Opera, Bruce Lawson, a very popular browser on mobile devices, stated (http://bit.ly/2e5Cgry) that native apps are a bridging technology.

That's a very bold statement, comparing the web to native applications. But it's something to think about. There are often many bridging technologies that lead to the real consumable product.

For example, Netflix began by shipping DVDs in the mail. I'm sure you could still do that today, but the vast majority of Netflix members simply stream and download video content to watch. The DVDs were a mere bridging technology to get the company started and form a relationship with a very loyal customer base.

The expenses involved in distributing those DVDs became too much for them to make it their primary distribution channel. As technology improved, which led to an increase in broadband, Netflix was able to shed the bridging distribution technology and focus on the original goal of getting videos and movies the living rooms of members all over the world.

In much the same way, mobile was a brand-new platform for building application experiences. And just like desktop computing, it started with native applications, and the web eventually won them over. The web won the desktop just as mobile technology emerged, and it emerged in a big way.

PWA signify a retooling of the web to make it a mobile first platform. Your applications can run faster, work offline, and ask users for permission to be on their homescreen. Never before have we been able to deploy these experiences at this level on the web.

Peak app

Smartphone owners always lookout to download apps they think will be useful. If you are fortunate enough to have a consumer download your application, then odds are that they will delete it after one use if they find it troublesome or difficult to use.

According to a Nielsen study (http://www.nielsen.com/us/en/insights/news/2015/so-many-apps-so-much-more-time-for-entertainment.html) that average adult uses less than 30 apps per month. Over time the lack of using an app leads to the unused apps being purged.

Several studies estimate roughly 10% of apps are used enough times to be retained. This means even if your app is downloaded the odds are it will eventually be removed and probably never used.

Brands are spending between $8-12 in advertising to earn a single application download. This means the true customer acquisition cost is roughly $80-120. Good luck recuperating that expense.

The Apple and Google App Store's boast of 2 million or more applications. Some, dated, research shows nearly 60% of apps are never downloaded.

Apple recently made the barrier to success even higher by enforcing section 4.2.6 of their application guideline requirements. This section gives them the authority to reject and remove apps at their discretion. They have been purging apps in mass they don't consider meet these arbitrary guidelines.

Why have consumers stopped downloading applications? Space, both physical and temporal. Mobile phones and tablets only have so much disk space. Many applications now need 100 MB-1 GB of space. While a few 128 GB iPhones are sold, the typical iPhone size is 32 GB. After personal photos, videos, and music, there is little to no room for applications.

While we have become a society that can never seem to leave our mobile screens, there is still only so much time in a day. Market analysts pay close attention to what we do with our screen time. Kids watch videos and play silly games. Adults live in social media with Facebook and Snapchat owning their phones. Adults also play silly games, such as 2048.

Out of the top five applications one these App Stores, Facebook owns three. The average adult spends over 2 hours a day in the Facebook universe looking at photos and videos. Text messaging is being replaced with Facebook Messenger. Millennials are addicted to Instagram, sharing, liking, and commenting on photos and videos non-stop.

Facebook, Facebook Messenger, and Facebook-owned Instagram are the top three mobile applications. They are followed by YouTube, SnapChat, and Gmail. Two of those are owned by Google. After those applications, the distribution curve drops to nearly zero.

We, mobile consumers, have settled into usage habits and have found that the need for applications has passed.

Installing an application, even if it is free, consists of eight steps, each step losing 20% of the initial interested base. The reason Amazon implemented one click purchasing was to eliminate friction and increase sales.

The web is relatively frictionless. You click a link in an email or maybe search for something, clicking the best perceived result, and within a few seconds you have downloaded or installed the web page you need. Little to no friction and next to no device resources have been used.

In contrast to the distribution of app usage in a given month, the average consumer visits over 100 websites. That is roughly 20 times more variety than their application distribution. This means there is more opportunity to engage customers via the web than native applications.

The web satisfies two important consumer requirements of minimal resource investment. Very little time or disk space is needed. In fact, they do not need to uninstall your website when they clean out their device so that they can make more videos to share on Instagram.

This is where PWA have risen in importance. Companies want their icons on consumer's devices. This symbolizes a relationship and hopefully increases sales or other engagement statistics. When brand engagement is cheap for the customer, they are more likely to take the step to make you part of their daily life.

Browsers are providing the engagement platform, but you still need to meet their requirements. That is what you are going to learn in this book.

PWA features

Don't mistake PWAs as a specific technology. It is more of a marketing term describing the usage of modern platform features to provide a certain quality of experience. Without good user experience, the technology does not matter.

The Chrome team has identified four experience factors a PWA should offer:

  • Fast
  • Reliable
  • Engaging
  • Integrated

Research has shown that 53% of users will abandon a site if it takes longer than 3 seconds to load. Service worker caching makes page load time almost instant, but it cannot make animations faster. This requires knowledge of CSS animations and possibly JavaScript.

Applications that stutter or jump around the screen are said to be janky. If you have ever loaded a web page, for example, almost any news website, and had the content jump up or down just as you start reading, you know what I am talking about. This is a very poor user experience and can easily be avoided with proper coding practices.

Later in this book, you are going to learn about RAIL (Response, Animation, Idle, Load) and the PRPL (Push, Render, Pre-cache, and Lazy- load) patterns. These are coding best practices offered by the Chrome team because they understand how browsers work. They, and the other browsers, want the web to work for everyone.

Browser vendors are offering guidance to help developers create the class of web applications that will earn a place on customer's homescreens. This guidance starts with a mobile performance first approach.

Consumers need to have confidence in an application, and they need to know that the application is reliable. This means it should just work when called upon. To enable this, a web application should load if the device is online, offline, and anything in-between.

Service worker caching provides a proxy layer between the browser and the network. This makes the network a progressive enhancement. It also introduces a new class of programming web developers must master.

Later in this book, you are going to learn about different caching strategies and how to employ them in different scenarios to make websites just work.

Service workers open up a new layer of opportunity where web developers can add valuable features that improve performance, engagement, and data management. Service workers are designed to be extensible so future capabilities can be added. Right now, caching, push notifications, and background sync are supported, but there are many other features being debated in the W3C working groups.

Push notifications give you the ability to connect with a consumer any time you wish, increasing engagement. As shared earlier, both the Weather Channel and Lancôme increased engagement via push notifications.

Background sync is a channel you can now use to let your application run when the network is unavailable. When connectivity is restored, you can seamlessly synchronize with the server without disrupting the user. Their phone may even be in their pocket while your application catches up.

A web application needs to engage users enough that they will want to make it a permanent fixture on their devices. Once your web application has the minimum technical requirements—a web manifest, registered service worker with a fetch event handler, and served via HTTPS—the browser triggers native prompts for the user to add the web application to their homescreen. You will delve more deeply into this experience as this book progresses.

The web manifest, HTTPS, and service worker require different expertise to execute effectively. And in my opinion, they increase in complexity from the latter. That is why embracing PWA is often called a journey. It's something you can, and should, implement in steps.

PWA advantages

I teased you with the advantages the web has over native applications, but how do these advantages elevate the web's past native applications?

Let's borrow a demonstration from the Chrome team. An XY graph can show the differences between the web and native applications. The vertical axis represents Capabilities. The x-axis represents Reach. The reach being defined is how easy it is to discover and quickly access the application or website:

For many years, native applications enjoyed a capability advantage. They had tight native platform APIs and hooks that enabled native applications to do things that the web was not designed to do. For example, native push notifications allow brands to send messages to customers without the application being open.

However, apps are gated behind closed App Stores on Apple, Android, and even the Microsoft ecosystem. This makes finding applications very difficult. Many estimates show it takes between $8 and $12 a day to get a single app download.

The web, as I mentioned earlier, simply was not ready for this shift to mobile. There have been several APIs such as geo-location and some web notification capabilities. These APIs are not necessarily on the same level with their native counterparts.

Developers have lacked awareness of many modern APIs. Unfortunately, this lack of knowledge and confidence has caused websites to not take advantage of these capabilities.

Ten years ago, responsive design did not exist. However, today, not only do we have CSS media queries and a vast array of responsive CSS libraries, but we also have responsive images built-in to browsers. Now, websites can offer layouts and download appropriately sized images for all screen sizes without crazy hacks.

Compared to their native counterparts, websites have always been easily discoverable. You can advertise a domain in any media channel and people know how to load it. Search engines are much more sophisticated than App Stores and provide an easy interface to find just about anything. The big advantage search engines have over App Stores is the ability to deeply index web content.

Search engines index pages deep within a website and thousands upon thousands of web pages per site. App stores can only offer a single point of entry to download the app. The only page you have control of is a sales page. In that one page, you need to sell your app without the customer sampling your content and experience. Reach is and has always been the web's greatest superpower:

As the graph visualizes, the web is not only on equal footing with native applications—it exceeds native applications is most cases. Sure, there are still going to be edge cases where a native application is the best choice, but these are shrinking every time a browser adds a new feature.

PWA technical requirements

At a minimum, there are three core technical requirements to be a PWA. A website must have a web manifest file, be served using HTTPS, and must register a service worker with a fetch event handler. You will dive deeper into each one of these requirements in future chapters.

The web manifest drives the Add to Homescreen experience. HTTPS provides a layer of security and trust between your application and the browser. The service worker provides the extensible backbone for event-driven functionality to execute on a separate thread from the user interface.

A PWA should also use an application shell or common HTML and CSS. This is the most common application of Chrome, which is used on just about every page on the site. If you have any experience with single page applications, you should understand what an application shell is.

The application shell

A typical application shell typically contains a header, a main content area, and a footer. Of course, this can vary by application and site. The 2048 game differs because there is only one web page:

Application shells are common-place in single page applications because they dynamically render markup and data in the browser. This does not need to be the case with a PWA. The reason single page applications are so popular is their ability to create a more native-like transition experience because there is no request delay when a new page is requested.

Since a PWA can be cached locally, this does not mean you need a true application shell. If the application utilizes a cache first strategy, pages can load in a matter of milliseconds, often less than 100. This is perceived as instant by the human mind.

This does not mean you should not identify an application shell. Server and build rendering engines can use the application shell and an array of layouts to create server hosted markups. You will be exposed to this so that you can work as we build the photo gallery and podcast application.

2048

A few years ago, a popular application was a simple game called 2048. The goal is to combine blocks with numbers to ultimately total 2048. Blocks are numbered in multiples of 2. You can combine adjacent blocks with the same value to create a new block with their combined value.

I wasted more time playing this game than I care to admit. It is easy to play and highly addictive. A well-crafted brew of endorphins and gameplay.

Fortunately, there were numerous open source knock-offs available on GitHub. Several were web applications. I would wager that native versions distributed through app stores were websites wrapped in a native shell, a hybrid application.

I chose a popular repository to fork for the book. The 2048 web application is simple and a perfect candidate to demonstrate how to make an exemplary PWA example:

The source code

The original application source code is available on GitHub (https://github.com/gabrielecirulli/2048). You can clone the repository and open it in a browser to play the game. Just be forewarned that it is addictive and could distract you from learning how to create PWAs.

I forked the repository in my GitHub profile (https://github.com/docluv/2048). My version adds the manifest, icons, service workers, and applies some code upgrades to make the application perform better and take advantage of newer APIs and browser features. The original code was written very well, but this was for browser capabilities of 3 years ago.

Feel free to star, clone, and fork my GitHub repository to customize it to your liking. A working version of the final application created in this book is available online (https://2048.love2dev.com/).

The application's code structure

Let's review how the game's source code is structured. I like this project because the code is simple and demonstrates how much can be accomplished with a small amount of code in the browser.

There are three asset folders: js, meta, and style. They contain JavaScript files, images, and style sheets that are needed to render and execute the game.

You will also notice a node_modules folder. I added a local web server using grunt connect, which is a node module. The original game works just fine if you load the index.html file directly in the browser. However, due to security constraints, a service worker does not function without a web server. I will cover this in more detail shortly.

At the root-level, there are only handful of web application files:

  • index.html
  • manifest.json
  • sw.js
  • favicon.ico

The nice thing about the 2048 code is that it only requires a single HTML file. The manifest.json and sw.js files add the PWA functionality we are after. The favicon.ico file is the icon loaded by the browser for the address bar:

Adding node modules to the project

The original repository is a stand-alone game, meaning it does not require a web server to execute, just a browser. You can right-click the index.html file and choose to open it in your favorite browser. You can still do this after registering a service worker and may not notice any differences. But if you open the browser console (F12 Developer Tools), you will most likely see an error.

This error can be attributed to service worker requirements. Service workers, like most new APIs supported by browsers, require HTTPS protocol. This requirement raises the default security level and gives the browsers a minimum level of trust in your site ownership.

The service worker specification relaxes this requirement for localhost addresses. Localhost is a common way to reference your local machine, which is typically a development environment. Because it is unlikely you are going to hack yourself, browsers tend to let you do what you want—except when you open files directly from the file system.

When localhost is used to load an asset, the browser is making a traditional network request, which requires a web server to respond. This means you, the user of the local machine, has gone through the effort of launching a local web server. This is not something the average consumer knows how to do.

A file, opened from the file system, is different. Anyone can send you an index.html file that loads scary code, designed to steal your identity or worse show endless loops of cat videos! By not honoring the direct file system, access browsers are protecting you from registering a malicious service worker script. Trusting a localhost web server makes development easier by avoiding the messy process of registering a localhost SSL certificate.

There are a variety of local web servers you can run. In recent years, my preference is node connect, which I execute as a Grunt task (https://love2dev.com/blog/make-a-local-web-server-with-grunt-connect/). Because connect is a node module, you can launch it directly from the command line or a custom script. There are modules for your favorite task runner, such as Gulp and so on. Besides, node is cross-platform, so everyone can use connect.

If you are familiar with installing node modules, you can skip ahead. If node and connect are new to you, this section will serve as a simple primer to get you up and running to run all the samples applications in this book on your local machine.

The first step to loading a node module is to install them from https://www.npmjs.com/ or one of the emerging package manager sites. You can manage this from the command line if you like, or you can define the modules needed in a package.json file.

You can read more about the package.json format here (https://docs.npmjs.com/files/package.json). For our purposes, grunt and the grunt-contrib-connect module are devDependencies. You could also define a dependencies section if this were a node application.

Grunt is a task runner that gained popularity several years ago and is still my preferred task runner. Task runners, and there seems to be a new one every week, help you organize repeatable tasks into repeatable recipes. I use Grunt and custom node scripts to build and deploy my PWAs. Think about your task runner as a command-line control panel to manage your application:

{
"name": "2048",
"version": "1.0.0",
"description": "2048 Progressive Web App",
"author": "Chris Love",
"private": true,
"devDependencies": {
"grunt": "*",
"grunt-contrib-connect": "*"
}
}

Both Grunt and the Grunt connect module are node packages and must be downloaded in order to execute. The package.json file gives npm a configuration so it can manage your packages. This way, you can quickly set up your project on any machine without having to maintain your node dependencies as part of the source code.

If you have cloned the sample repository, you will note that the node modules were excluded from the source code. That's because they are not part of the application itself. They are a dependency and npm helps you recreate the desired environment.

To install the packages, you need to open a command line and change to your source code's folder. Next, you must execute the following command:

>npm install

This kicks off the npm installation process, which downloads your modules and their dependency chain. When completed, you have everything you need to run or build your application.

Next, you will need to create a gruntfile.js. This is where you tell Grunt what tasks you want to run and how you want them to run. If you want to know the details of using Grunt, visit their website (https://gruntjs.com/):

module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-connect');
// Project configuration.
grunt.initConfig({
connect: {
localhost: {
options: {
port: 15000,
keepalive: true
}
}
}
});
};

Since we are only using the connect module, the 2048 gruntfile is very simple. You need to tell Grunt to load the connect module, then register the task to run in the initConfig function.

2048 is a very simple application, which keeps our customization to a minimum. I arbitrarily chose port 15000 to serve the application and chose to have keepalive open. There are many options you can define. More details are available on the grunt-contrib-connect npm page (https://www.npmjs.com/package/grunt-contrib-connect).

The only task left to do is start the connect web server. This is done from the command line. If you still have the command line open from when you performed the npm install, you can reuse it. If not, repeat the process of opening a command line and changing to the project's folder:

>grunt connect
Running "connect:localhost" (connect) task
Waiting forever...
Started connect web server on http://localhost:15000

Execute grunt connect and you should see the preceding example output. Note that the command continues to execute. This is because it is a server, listening to requests on port 15000. You cannot execute additional commands at this prompt.

You can now load the 2048 game in your browser by entering http://localhost:15000 in the address bar.

Adding a manifest

Adding a web manifest file should be the first step in upgrading an existing website. You can create your site's manifest file in a matter of minutes. In the tooling chapter, I will review a few online resources that can help automate the process.

Registering a PWA's web manifest requires a special link element in the HTML head element. The following code shows how the 2048 manifest file is registered:

<head>
….
<link rel="manifest" href="manifest.json">
</head>

If you are familiar with referencing a style sheet, this syntax should look familiar. The difference is the rel attribute value being manifest. The href value points to the manifest file. You are free to name it anything, but manifest is the most common name.

The next chapter will go into more manifest file details. You can reference the project's manifest.json file to see how the 2048 game is configured. It contains the application's name, default URL, primary colors, and an array of icon image references.

Adding a service worker

Next, you need to register a service worker. This is done in what I call the client-side code, which is the JavaScript you are accustomed to writing. Service workers execute in a separate thread from the UI. I think about it as a background process. You still need to register the service worker for the site.

For simple registrations, like this example, my preferred method is a script block at the bottom of my site's markup. First, detect if service workers are supported. If they are, then attempt to register the site's service work. If the browser does not support service workers, skip the registration code so no exceptions occur.

Registration is done by calling the navigator.serviceWorker.register function. It accepts a single argument, which is a path to the service worker file. I will review more rules around this in later chapters.

The register function returns a promise. You can add code to log successful registration as follows:

      <script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function
(registration) { // Registration was successful
console.log('ServiceWorker registration successful with
scope: ', registration.scope);
}).catch(function (err) { // registration failed :(
console.log('ServiceWorker registration failed: ',
err);
});
}
</script>

We will start diving into details about service workers in Chapter 5, The Service Worker Life Cycle. To help you understand the example code, let me introduce some service worker fundamentals. Service workers are completely asynchronous. They enter an idle or sleep state if they are not needed. They wake up or spin up completely in response to the operating system or browser firing and events.

All logic execution is a product of events. You must register event handlers to execute your service worker logic. The 2048 service worker registers event handlers for the install, activate, and fetch events.

The 2048 game service worker pre-caches the entire application in the install event. You will learn more about caching strategies in Chapter 6, Master the Cache API – Manage Web Assets in a Podcast Application. For now, we will cache the application so it is available all the time, without any network chatter:

self.addEventListener("install", function (event) {
console.log("Installing the service worker!");
caches.open("PRECACHE")
.then(function (cache) {
cache.addAll(cacheList);
});
});

The 2048 service worker caches assets in the install event. The application assets are defined in an array in the server worker code. The cache API provides an interface to a special storage designed specifically to persist response objects. I will defer the details to later chapters:

var cacheList = [
"index.html",
"style/main.css",
"js/keyboard_input_manager.js",
"js/html_actuator.js",
"js/grid.js",
"js/tile.js",
"js/local_storage_manager.js",
"js/game_manager.js",
"js/application.js"
];

The service worker also has an activate and a fetch event handler. A fetch event handler must be registered before the add to homescreen feature can be triggered.

The fetch event fires when the browser requests an asset from the network. This could be an image, stylesheet, script, AJAX call, and so on. The event parameter contains the request object and can be used to check your cache to see if the asset is available:

self.addEventListener("fetch", function (event) {
event.respondWith(
caches.match(event.request)
.then(function (response) {
if (response) {
return response;
}
return fetch(event.request);
})
);
});

Without a fetch event handler, your application cannot work offline. There is no requirement that the handler catch any requests, just that it is registered. It is a minimal check for offline capability.

In the example fetch event handler, all caches are interrogated to see if there is an existing match to the request. If so, the locally cached version is returned. If not, the request is passed to the network.

That's it; congratulations! Your website is now a PWA, at least on your local machine:

At this point, loading the 2048 localhost site in Chrome should cause an add to homescreen prompt being displayed. If not, reload the page once or twice and apply focus to the browser tab. If you are still not seeing the prompt, check the console for any error messages and debug them accordingly.

Summary

In this chapter, you have learned the basics of PWAs by updating a basic game website. We also reviewed what progressive websites are and why they were created.

In the next chapter, you will learn more details about the homescreen prompt experience and how to make a proper web manifest file.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Explore different models and patterns required to develop progressive web applications
  • • Create applications requiring shorter runtime for attracting more users
  • • Study different projects to understand the fundamentals of progressive web applications

Description

Are you a developer that wants to create truly cross-platform user experiences with a minimal footprint, free of store restrictions and features customers want? Then you need to get to grips with Progressive Web Applications (PWAs), a perfect amalgamation of web and mobile applications with a blazing-fast response time. Progressive Web Application Development by Example helps you explore concepts of the PWA development by enabling you to develop three projects, starting with a 2048 game. In this game, you will review parts of a web manifest file and understand how a browser uses properties to define the home screen experience. You will then move on to learning how to develop and use a podcast client and be introduced to service workers. The application will demonstrate how service workers are registered and updated. In addition to this, you will review a caching API so that you have a firm understanding of how to use the cache within a service worker, and you'll discover core caching strategies and how to code them within a service worker. Finally, you will study how to build a tickets application, wherein you’ll apply advanced service worker techniques, such as cache invalidation. Also, you'll learn about tools you can use to validate your applications and scaffold them for quality and consistency. By the end of the book, you will have walked through browser developer tools, node modules, and online tools for creating high-quality PWAs.

Who is this book for?

Progressive Web Application Development by Example is for you if you’re a web developer or front-end designer who wants to ensure improved user experiences. If you are an application developer with knowledge of HTML, CSS, and JavaScript, this book will help you enhance your skills in order to develop progressive web applications, the future of app development.

What you will learn

  • • Explore the core principles of PWAs
  • • Study the three main technical requirements of PWAs
  • • Discover enhancing requirements to make PWAs transcend native apps and traditional websites
  • • Create and install PWAs on common websites with a given HTTPS as the core requirement
  • • Get acquainted with the service worker life cycle
  • • Define service worker caching patterns
  • • Apply caching strategies to three different website scenarios
  • • Implement best practices for web performance
Estimated delivery fee Deliver to Great Britain

Standard delivery 1 - 4 business days

£4.95

Premium delivery 1 - 4 business days

£7.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jul 24, 2018
Length: 354 pages
Edition : 1st
Language : English
ISBN-13 : 9781787125421
Vendor :
Google
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Great Britain

Standard delivery 1 - 4 business days

£4.95

Premium delivery 1 - 4 business days

£7.95
(Includes tracking information)

Product Details

Publication date : Jul 24, 2018
Length: 354 pages
Edition : 1st
Language : English
ISBN-13 : 9781787125421
Vendor :
Google
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
£169.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts
£234.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 102.97
React Cookbook
£36.99
Progressive Web Application Development by Example
£32.99
Mastering The Faster Web with PHP, MySQL, and JavaScript
£32.99
Total £ 102.97 Stars icon
Banner background image

Table of Contents

11 Chapters
Introduction to Progressive Web Apps Chevron down icon Chevron up icon
Creating a Home Screen Experience with a Web Manifest Chevron down icon Chevron up icon
Making Your Website Secure Chevron down icon Chevron up icon
Service Workers – Notification, Synchronization, and Our Podcast App Chevron down icon Chevron up icon
The Service Worker Life Cycle Chevron down icon Chevron up icon
Mastering the Cache API - Managing Web Assets in a Podcast Application Chevron down icon Chevron up icon
Service Worker Caching Patterns Chevron down icon Chevron up icon
Applying Advanced Service Worker Cache Strategies Chevron down icon Chevron up icon
Optimizing for Performance Chevron down icon Chevron up icon
Service Worker Tools Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela