The Complete Video Solution for Web and Mobile Developers

This article was originally published on Cloudinary Blog. Thank you for supporting the partners who make SitePoint possible. Videos in web sites and apps are starting to catch up with images in terms of popularity and they are a constantly growing part of the media strategy for most organizations. This means bigger challenges for developers […]

Continue reading %The Complete Video Solution for Web and Mobile Developers%


Source: Sitepoint

Inheritance and Extending Objects With JavaScript

If you are familiar with object-oriented programming, you are most likely familiar with subclassing and inheritance. However, inheritance has been getting a bad rap. I believe that is because some developers see it as a catch-all solution when you need to modify a program. The problem with this is that class hierarchies can become unmanageable. 

There are other design patterns we can use to make our apps easier to understand and ready for change. I will show you examples of how you can use inheritance and the decorator and composite pattern to improve your program’s design.

Inheritance

The idea behind inheritance is that one object “is a” specialized version of another object. There is a parent class (also known as a superclass) which defines the base properties of our object. And there is a child class (subclass) that inherits the properties of the parent class. 

An example of inheritance is a dog and a poodle. All dogs have certain features like four legs and the ability to bark. A poodle “is a” kind of dog. An SUV is a vehicle. A circle is a shape. This is what our class hierarchy would look like if we were designing a program for creating shapes.

A basic inheritance diagram

The benefit of having a Shape class is that we can reuse the properties and methods we defined in other classes. 

Notice that the getArea method was redefined in each of our subclasses. We did not have to redefine this method, but we did it to replace our parent’s implementation of the method. That is because each shape will have its own way of calculating the area. 

Overriding a parent method in a child class is an example of polymorphism. Polymorphism is the ability for objects to have multiple forms. It allows subclasses to have methods with the same name as their superclass but with different implementations.  

This is an example of what our code would look like for creating a Shape and Circle subclass:

One of the drawbacks to this design choice is that if you decide the parent class needs to change, then the subclasses may need to change too, along with all the objects we created. 

For example, suppose we decided later on that it would be better to replace the x and y parameters of the Shape class with an object. Consequently, we would need to change the constructor for all of our subclasses and the arguments for every object we instantiated.

We can see how this can easily become problematic. We would have to make sure we got our design right the first time around so that we could avoid making a change. But that is not practical, nor is it what we should be striving for. A program is an ever-evolving entity, and it’s better for us developers if we have the flexibility to make changes easily. At the very least, we should not have more than one level of child classes.

Decorator Pattern

A decorator allows us to attach properties to an object after they have been created. This means we can add functionality without subclassing or being concerned with the implementation of our object. 

Instead of thinking a circle is a shape, we could use the Shape class to create circles and wrap it with the additional properties we want. Here is an alternative to creating circle objects using a decorator:

We can add or modify members of our Shape class with a decorator as opposed to subclassing it. With our shapes example, you might find that you just want to create a circle object that has all of the properties you need and do the same for other shapes. That is fine. But a decorator allows us to reuse the code in our Shape class and modify it with the functionality that differs with each shape. As a result, we will have more objects, but more objects are easier to manage than more subclasses.

This pattern is not limited to creating graphics. You can use it in any situation where you want to add responsibilities to an object. 

For example, we may have a class that handles signing up users to our account. Before we save their information to our database, it would be wise to check that the input is valid and doesn’t contain any malicious scripts. We could decorate the class with a method to validate the information first. This same decorator can be reused anywhere in our application where we accept user input.

Composite Pattern

Objects can be composed of other objects. The view for an app can be thought of as a component that is composed of other views. If we were making a game, our game world would display all our graphics we created like circles and squares. Every time we update our view, we would need to redraw every element. We need a way to manage all of the elements as a group. 

That is where the composite pattern can help us. We can create a class that is responsible for all of the elements. When we want to redraw the elements, we call this class’s draw method, and it will call the draw method on each individual element.  

A webpage can also be thought of as a component. This component could have a menu, a sidebar, and a blog post. The post would be a sub-component that has a picture, a title, and a body. The draw method for our main app component will call draw on the menu, sidebar, and post. The post component will in turn call draw on the post image, title, and body. 

Here is a view of what a web page would like divided into components:

The Composite Pattern

This pattern isn’t limited to creating views. For example, if we were making a game, we might have a component to manage the elements on the screen, a component to manage the audio, and a component to manage the game state. 

These would all be inside a component I call the game engine. The game engine would have an initialize method that would call the initialize method on each of its sub-components. That is the power in using the composite pattern. Instead of dealing with individual objects, we can treat them as one object.  

Conclusion

Inheritance lets us reuse code by defining an object in terms of another object. The decorator pattern allows us to add responsibilities to an object without changing the original code or subclassing. The composite pattern models part-whole relationships. These patterns aren’t meant to be used in isolation. 

JavaScript has become the language of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available on Envato Market.

They can be combined as you see fit. The examples I provided also should not be taken as the only application for using the patterns. They are just a guide. Feel free to use your creativity to apply them. There is no one way to implement them or one use case.


Source: Nettuts Web Development

Cheerful Wallpapers To Deck Your December Desktop (2017 Edition)

To get you in the right mood for December and the upcoming holiday season, artists and designers from across the globe once again got their creative ideas bubbling and created festive and inspiring desktop wallpapers for you. Wallpapers that are a bit more distinctive as the usual crowd and that are bound to add some holiday cheer to your screen.
All wallpapers featured in this post can be downloaded for free and come in versions with and without a calendar for December 2017.
Source: Smashing Magazine

PHP-FPM tuning: Using ‘pm static’ for Max Performance

Let’s take a very quick look at how best to set up PHP-FPM for high throughput, low latency, and a more stable use of CPU and memory. By default, most setups have PHP-FPM’s PM (process manager) string set to dynamic and there’s also the common advice to use ondemand if you suffer from available memory issues. However, let’s compare the two management options based on php.net’s documentation and also compare my favorite for high traffic setup — static pm:

  • pm = dynamic: the number of child processes is set dynamically based on the following directives: pm.max_children, pm.start_servers, pm.min_spare_servers, pm.max_spare_servers.

  • pm = ondemand: the processes spawn on demand when requested, as opposed to dynamic, where pm.start_servers are started when the service is started.

  • pm = static: the number of child processes is fixed by pm.max_children.

See the full list of global php-fpm.conf directives for further details.

PHP-FPM Process Manager (PM) Similarities to CPUFreq Governor

Now, this may seem a bit off topic, but I hope to tie it back into our PHP-FPM tuning topic. Okay, we’ve all had slow CPU issues at some point, whether it be a laptop, VM or dedicated server. Remember CPU frequency scaling? (CPUFreq governor.) These settings, available on both *nix and Windows, can improve the performance and system responsiveness by changing the CPU governor setting from ondemand to performance. This time, let’s compare the descriptions and look for similarities:

  • Governor = ondemand: scales CPU frequency dynamically according to current load. Jumps to the highest frequency and then scales down as the idle time increases.

  • Governor = conservative: scales the frequency dynamically according to current load. Scales the frequency more gradually than ondemand.

  • Governor = performance: always run the CPU at the maximum frequency.

See the full list of CPUFreq governor options for further details.

Notice the similarities? I wanted to use this comparison first, with the aim of finding the best way to write an article which recommends using pm static for PHP-FPM as your first choice.

With CPU governor, the performance setting is a pretty safe performance boost because it’s almost entirely dependent on your server CPU’s limit. The only other factors would be things such as heat, battery life (laptop) and other side effects of clocking your CPU frequency to 100% permanently. Once set to performance, it is indeed the fastest setting for your CPU. For example read about the ‘force_turbo’ setting on Raspberry Pi, which forces your RPi board to use the performance governor where performance improvement is more noticeable due to the low CPU clock speeds.

Using ‘pm static’ to Achieve Your Server’s Max Performance

The PHP-FPM pm static setting depends heavily on how much free memory your server has. Basically, if you are suffering from low server memory, then pm ondemand or dynamic may be better options. On the other hand, if you have the memory available, you can avoid much of the PHP process manager (PM) overhead by setting pm static to the max capacity of your server. In other words, when you do the math, pm.static should be set to the max amount of PHP-FPM processes that can run without creating memory availability or cache pressure issues. Also, not so high as to overwhelm CPU(s) and have a pile of pending PHP-FPM operations.

Linux top php-fpm static pm

In the screenshot above, this server has pm = static and pm.max_children = 100 which uses a max of around 10GB of the 32GB installed. Take note of the self explanatory highlighted columns. During that screenshot there were about 200 ‘active users’ (past 60 seconds) in Google Analytics. At that level, about 70% of PHP-FPM children are still idle. This means PHP-FPM is always set to the max capacity of your server’s resources regardless of current traffic. Idle processes stay online, waiting for traffic spikes and responding immediately, rather than having to wait on the pm to spawn children and then kill them off after x pm.process_idle_timeout expires. I have pm.max_requests set extremely high because this is a production server with no PHP memory leaks. You can use pm.max_requests = 0 with static if you have 110% confidence in your current and future PHP scripts. However, it’s recommended to restart scripts over time. Set the number of requests to a high number since the point is to avoid pm overhead. So for example at least pm.max_requests = 1000 depending on your number of pm.max_children and number of requests per second.

The screenshot uses Linux top filtered by ‘u’ (user) option and the name of the PHP-FPM user. The number of processes displayed are only the ‘top’ 50 or so (didn’t count), but basically top displays the top stats which fit in your terminal window — in this case, sorted by %CPU. To view all 100 PHP-FPM processes you can use something like:

top -bn1 | grep php-fpm

Continue reading %PHP-FPM tuning: Using ‘pm static’ for Max Performance%


Source: Sitepoint

From Idea To Reality: Designing An App With Sketch And Xcode

Everyone has an idea for a mobile app, from your mom to the guy you met in line at the grocery store. You might even be one of those people, if you are reading this tutorial. Building your own app really gives you the ability to create anything you can imagine. For some people, the idea is the easy part; when it comes to making it a reality, they have no clue where to start.
Source: Smashing Magazine

23 Development Tools for Boosting Website Performance

When dealing with performance, it’s hard to remember all the tools that might help you out during development. For that purpose, we’ve compiled a list of 23 performance tools for your reference. Some you’ll have heard of, others probably not. Some have been covered in detail in our performance month, others are yet to be covered future articles; but all are very useful and should be part of your arsenal.

Client-side Performance Tools

1. Test your Mobile Speed with Google

Google’s Test My Site is an online tool offered by Google and powered by the popular website performance tool WebPageTest.org.

Google’s Test My Site

You can either visualize your report on site or have it emailed to you via your email address.

Google’s Test My Site: Loading time

The tool gives you your website loading time (or Speed Index) calculated using a Chrome browser on a Moto G4 device within a 3G network. It also gives you the estimated percentage of visitors lost due to loading time. Among other things it also:

  • compares your site speed with the top-performing sites in your industry
  • gives you top fixes that can help you speed up your website loading time.

2. SiteSpeed.io

SiteSpeed.io is an open-source tool — or a set of tools — that can help you measure your website performance and improve it.

  • Coach: gives you performance advice and fixes for your website based on best practices.
  • Browsertime: collects metrics and HAR files from your browser.
  • Chrome-HAR: helps you compare HAR files.
  • PageXray: extracts different metrics (from HAR files) such as size, number of requests, and so on.

You can install these tool(s) using npm:

npm install sitespeed.io -g
sitespeed.io --help

Or Docker:

docker run --shm-size=1g --rm -v "$(pwd)":/sitespeed.io sitespeedio/sitespeed.io https://www.sitespeed.io/ --video --speedIndex

3. Lighthouse by Google

Lighthouse is an open-source tool for running audits to improve web page quality. It’s integrated into Chrome’s DevTools and can be also installed as a Chrome extension or CLI-based tool. It’s an indispensable tool for measuring, debugging and improving the performance of modern, client-side apps (particularity PWAs).

Lighthouse performance

You can find the extension from the Chrome Web Store.

Or you can install Lighthouse, from npm, on your system with:

npm install -g lighthouse

Then run it with:

lighthouse <url>

You can use Lighthouse programmatically to build your own performance tool or for continuous integration.

Make sure to check these Lighthouse-based tools:

  • webpack-lighthouse-plugin: a Lighthouse plugin for Webpack
  • treo: Lighthouse as a service with a personal free plan.
  • calibreapp: a paid service, based on Lighthouse, that helps you track, understand and improve performance metrics using real Google Chrome instances.
  • lighthouse-cron: a module which can help you track your Lighthouse scores and metrics overtime.

We’ve got an in-depth look at Lighthouse in our PWA performance month post.

4. Lightcrawler

You can use Lightcrawler to crawl your website then run each page found through Lighthouse.

Start by installing the tool via npm:

npm install --save-dev lightcrawler

Then run it from the terminal by providing the target URL and a JSON configuration file:

lightcrawler --url <url> --config lightcrawler-config.json

The configuration file can be something like:

{
  "extends": "lighthouse:default",
  "settings": {
    "crawler": {
      "maxDepth": 2,
      "maxChromeInstances": 5
    },
    "onlyCategories": [
      "Performance",
    ],
    "onlyAudits": [
      "accesskeys",
      "time-to-interactive",
      "user-timings"
    ]
  }
}

5. YSlow

YSlow is a JavaScript bookmarklet that can be added to your browser and invoked on any visited web page. This tool analyzes web pages and helps you discover the reasons for slowness based on Yahoo’s rules for high-performance websites.

You can install YSlow by dragging and dropping the bookmarklet to your browser’s bookmark bar. Find more information here.

6. GTmetrix

GTmetrix is an online tool that gives you insights into your website performance (fully loaded time, total page size, number of requests etc.) and also practical recommendations on how to optimize it.

GTmetrix report

7. Page Performance

Page performance

Page performance is a Chrome extension that can be used to run a quick performance analysis. If you have many tabs open, the extension will be invoked on the active tab.

8. The AMP Project

The AMP (Accelerated Mobile Pages) project is an open-source project that aims to make the web faster. The AMP project enables developers to create websites that are fast, high-performing and with great user experiences across all platforms (desktop browsers and mobile devices).

The AMP Project

The AMP project is essentially three core components:

  • AMP HTML: it’s HTML but with some restrictions to guarantee reliable performance.
  • AMP JS: a JavaScript library that takes care of rendering AMP HTML.
  • AMP Cache: a content delivery network for caching and delivering valid AMP pages. You can use tools such as AMP Validator or amphtml-validator to check if your pages are valid AMP pages.

Once you add AMP markup to your pages, Google will discover them automatically and cache them to deliver them through the AMP CDN. You can learn from here how to create your first AMP page.

Continue reading %23 Development Tools for Boosting Website Performance%


Source: Sitepoint

Designing Ethics: Shifting Ethical Understanding In Design

The influence of design is expanding beyond the realms of typography and objects and into healthcare, public policy, education, financial services, and more. Designers working in these emerging design fields are responsible for projects that have significant and fundamental impact on the quality of people’s lives with clear ethical implications.
In healthcare, for example, designers are responsible for creating everything from the industrial designer’s medical device that keeps a heart beating to the service designer’s physical layout of an operating room.
Source: Smashing Magazine

JavaScript Performance Optimization Tips: An Overview

In this post, there’s lots of stuff to cover across a wide and wildly changing landscape. It’s also a topic that covers everyone’s favorite: The JS Framework of the Month™.

We’ll try to stick to the “Tools, not rules” mantra and keep the JS buzzwords to a minimum. Since we won’t be able to cover everything related to JS performance in a 2000 word article, make sure you read the references and do your own research afterwards.

But before we dive into specifics, let’s get a broader understanding of the issue by answering the following: what is considered as performant JavaScript, and how does it fit into the broader scope of web performance metrics?

Setting the Stage

First of all, let’s get the following out of the way: if you’re testing exclusively on your desktop device, you’re excluding more than 50% of your users.

The number of mobile users overtook the number of desktop users in November 2016

This trend will only continue to grow, as the emerging market’s preferred gateway to the web is a sub-$100 Android device. The era of the desktop as the main device to access the Internet is over, and the next billion internet users will visit your sites primarily through a mobile device.

Testing in Chrome DevTools’ device mode isn’t a valid substitute to testing on a real device. Using CPU and network throttling helps, but it’s a fundamentally different beast. Test on real devices.

Even if you are testing on real mobile devices, you’re probably doing so on your brand spanking new $600 flagship phone. The thing is, that’s not the device your users have. The median device is something along the lines of a Moto G1 — a device with under 1GB of RAM, and a very weak CPU and GPU.

Let’s see how it stacks up when parsing an average JS bundle.

Ouch. While this image only covers the parse and compile time of the JS (more on that later) and not general performance, it’s strongly correlated and can be treated as an indicator of general JS performance.

To quote Bruce Lawson, “it’s the World-Wide Web, not the Wealthy Western Web”. So, your target for web performance is a device that’s ~25x slower than your MacBook or iPhone. Let that sink in for a bit. But it gets worse. Let’s see what we’re actually aiming for.

What Exactly is Performant JS Code?

Now that we know what our target platform is, we can answer the next question: what is performant JS code?

While there’s no absolute classification of what defines performant code, we do have a user-centric performance model we can use as a reference: The RAIL model.

Respond

If your app responds to a user action in under 100ms, the user perceives the response as immediate. This applies to tappable elements, but not when scrolling or dragging.

Animate

On a 60Hz monitor, we want to target a constant 60 frames per second when animating and scrolling. That results in around 16ms per frame. Out of that 16ms budget, you realistically have 8–10ms to do all the work, the rest taken up by the browser internals and other variances.

Idle work

If you have an expensive, continuously running task, make sure to slice it into smaller chunks to allow the main thread to react to user inputs. You shouldn’t have a task that delays user input for more than 50ms.

Load

You should target a page load in under 1000ms. Anything over, and your users start getting twitchy. This is a pretty difficult goal to reach on mobile devices as it relates to the page being interactive, not just having it painted on screen and scrollable. In practice, it’s even less:

In practice, aim for the 5s time-to-interactive mark. It’s what Chrome uses in their Lighthouse audit.

Now that we know the metrics, let’s have a look at some of the statistics:

  • 53% of visits are abandoned if a mobile site takes more than three seconds to load
  • 1 out of 2 people expect a page to load in less than 2 seconds
  • 77% of mobile sites take longer than 10 seconds to load on 3G networks
  • 19 seconds is the average load time for mobile sites on 3G networks.

And a bit more, courtesy of Addy Osmani:

  • apps became interactive in 8 seconds on desktop (using cable) and 16 seconds on mobile (Moto G4 over 3G)
  • at the median, developers shipped 410KB of gzipped JS for their pages.

Feeling sufficiently frustrated? Good. Let’s get to work and fix the web. ✊

Context is Everything

You might have noticed that the main bottleneck is the time it takes to load up your website. Specifically, the JavaScript download, parse, compile and execution time. There’s no way around it but to load less JavaScript and load smarter.

But what about the actual work that your code does aside from just booting up the website? There has to be some performance gains there, right?

Before you dive into optimizing your code, consider what you’re building. Are you building a framework or a VDOM library? Does your code need to do thousands of operations per second? Are you doing a time-critical library for handling user input and/or animations? If not, you may want to shift your time and energy somewhere more impactful.

It’s not that writing performant code doesn’t matter, but it usually makes little to no impact in the grand scheme of things, especially when talking about microoptimizations. So, before you get into a Stack Overflow argument about .map vs .forEach vs for loops by comparing results from JSperf.com, make sure to see the forest and not just the trees. 50k ops/s might sound 50× better than 1k ops/s on paper, but it won’t make a difference in most cases.

Continue reading %JavaScript Performance Optimization Tips: An Overview%


Source: Sitepoint

Designing For A Browserless Web

What happens when we take the web browser out of web browsing? Google’s new “Add to Homescreen” feature delivers fast, focused web experiences that are indistinguishable from those of a native app. What can designers learn from the successes of early adopters such as Twitter, and how can we leverage app-like design patterns to tackle this brand new set of user experience challenges?
The “Add to Homescreen” installation process, as shown on Google Chrome Developer’s mobile website (Image source) (Large preview) We’ve seen debates on the topic of native versus web experiences.
Source: Smashing Magazine

Progressive Web Apps: A Crash Course

Progressive Web Apps (PWAs) try to overlap the worlds of the mobile web apps and native mobile apps by offering the best features of each to mobile users.

They offer an app-like user experience (splash screens and home screen icons), they’re served from HTTPS-secured servers, they can load quickly (thanks to page load performance best practices) even in low quality or slow network conditions, and they have offline support, instant loading and push notifications. The concept of PWAs was first introduced by Google, and is still supported by many Chrome features and great tools, such as Lighthouse, an open-source tool for accessibility, performance and progressiveness auditing which we’ll look into a bit later.

Throughout this crash course, we’ll build a PWA from scratch with ES6 and React and optimize it step by step with Lighthouse until we achieve the best results in terms of UX and performance.

The term progressive simply means that PWAs are designed in a such a way that they can be progressively enhanced in modern browsers where many new features and technologies are already supported but should also work fine in old browsers with no cutting-edge features.

Native vs Mobile = Progressive

A native app is distributable and downloadable from the mobile OS’s respective app store. Mobile web apps, on the other hand, are accessible from within a web browser by simply entering their address or URL. From the user’s point of view, launching a browser and navigating to an address is much more convenient than going to the app store and downloading, installing, then launching the app. From the developer/owner’s point of view, paying a one-time fee for getting an app store account and then uploading their apps to become accessible to users worldwide is better than having to deal with the complexities of web hosting.

A native app can be used offline. In the case of remote data that needs to be retrieved from some API server, the app can be easily conceived to support some sort of SQLite caching of the latest accessed data.

A mobile web app is indexable by search engines like Google, and through search engine optimization you can reach more users. This is also true for native apps, as the app stores have their own search engines where developers can apply different techniques — commonly known as App Store Optimization — to reach more users.

A native app loads instantly, at least with a splash screen, until all resources are ready for the app to execute.

These are the most important perceived differences. Each approach to app distribution has advantages for the end user (regarding user experience, availability etc.) and app owner (regarding costs, reach of customers etc.). Taking that into consideration, Google introduced PWAs to bring the best features of each side into one concept. These aspects are summarized in this list introduced by Alex Russell, a Google Chrome engineer. (Source: Infrequently Noted.)

  • Responsive: to fit any form factor.
  • Connectivity independent: progressively-enhanced with service workers to let them work offline.
  • App-like-interactions: adopt a Shell + Content application model to create appy navigations & interactions.
  • Fresh: transparently always up-to-date thanks to the service worker update process.
  • Safe: served via TLS (a service worker requirement) to prevent snooping.
  • Discoverable: are identifiable as “applications” thanks to W3C Manifests and service worker registration scope allowing search engines to find them.
  • Re-engageable: can access the re-engagement UIs of the OS; e.g. push notifications.
  • Installable: to the home screen through browser-provided prompts, allowing users to “keep” apps they find most useful without the hassle of an app store.
  • Linkable: meaning they’re zero-friction, zero-install, and easy to share. The social power of URLs matters.

Lighthouse

Lighthouse is a tool for auditing web apps created by Google. It’s integrated with the Chrome Dev Tools and can be triggered from the Audits panel.

You can also use Lighthouse as a NodeJS CLI tool:

npm install -g lighthouse  

You can then run it with:

lighthouse https://sitepoint.com/

Lighthouse can also be installed as a Chrome extension, but Google recommends using the version integrated with DevTools and only use the extension if you somehow can’t use the DevTools.

Please note that you need to have Chrome installed on your system to be able to use Lighthouse, even if you’re using the CLI-based version.

Building your First PWA from Scratch

In this section, we’ll be creating a progressive web app from scratch. First, we’ll create a simple web application using React and Reddit’s API. Next, we’ll be adding PWA features by following the instructions provided by the Lighthouse report.

Please note that the public no-authentication Reddit API has CORS headers enabled so you can consume it from your client-side app without an intermediary server.

Before we start, this course will assume you have a development environment setup with NodeJS and NPM installed. If you don’t, start with the awesome Homestead Improved, which is running the latest versions of each and is ready for development and testing out of the box.

We start by installing Create React App, a project boilerplate created by the React team that saves you from the hassle of WebPack configuration.

npm install -g create-react-app
create-react-app react-pwa
cd react-pwa/

The application shell architecture

The application shell is an essential concept of progressive web apps. It’s simply the minimal HTML, CSS and JavaScript code responsible for rendering the user interface.

App Shell

This app shell has many benefits for performance. You can cache the application shell so when users visit your app next time, it will be loaded instantly because the browser doesn’t need to fetch assets from a remote server.

For building a simple UI we’ll use Material UI, an implementation of Google Material design in React.

Let’s install the package from NPM:

npm install material-ui --save

Next open src/App.js then add:

import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import {Card, CardActions, CardHeader,CardTitle,CardText} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import IconButton from 'material-ui/IconButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';

import logo from './logo.svg';
import './App.css';

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      posts: []
    };
  }

  render() {
    return (

      <MuiThemeProvider>
        <div>
          <AppBar
            title={<span >React PWA</span>}

            iconElementLeft={<IconButton><NavigationClose /></IconButton>}
            iconElementRight={<FlatButton onClick={() => this.fetchNext('reactjs', this.state.lastPostName)} label="next" />
            }
          />

          {this.state.posts.map(function (el, index) {
            return <Card key={index}>
              <CardHeader
                title={el.data.title}

                subtitle={el.data.author}
                actAsExpander={el.data.is_self === true}
                showExpandableButton={false}
              />

              <CardText expandable={el.data.is_self === true}>
                {el.data.selftext}
              </CardText>
              <CardActions>
                <FlatButton label="View" onClick={() => {
                  window.open(el.data.url);
                }} />

              </CardActions>
            </Card>
          })}


          <FlatButton onClick={() => this.fetchNext('reactjs', this.state.lastPostName)} label="next" />
        </div>
      </MuiThemeProvider>

    );
  }
}

export default App;

Next we need to fetch the Reddit posts using two methods fetchFirst() and fetchNext():

  fetchFirst(url) {
    var that = this;
    if (url) {
      fetch('https://www.reddit.com/r/' + url + '.json').then(function (response) {
        return response.json();
      }).then(function (result) {

        that.setState({ posts: result.data.children, lastPostName: result.data.children[result.data.children.length - 1].data.name });

        console.log(that.state.posts);
      });
    }
  }  
  fetchNext(url, lastPostName) {
    var that = this;
    if (url) {
      fetch('https://www.reddit.com/r/' + url + '.json' + '?count=' + 25 + '&after=' + lastPostName).then(function (response) {
        return response.json();
      }).then(function (result) {

        that.setState({ posts: result.data.children, lastPostName: result.data.children[result.data.children.length - 1].data.name });
        console.log(that.state.posts);
      });
    }
  }
  componentWillMount() {

     this.fetchFirst("reactjs");
}

You can find the source code in this GitHub Repository.

Before you can run audits against your app you’ll need to make a build and serve your app locally using a local server:

npm run build

This command invokes the build script in package.json and produces a build in the react-pwa/build folder.

Now you can use any local server to serve your app. On Homestead Improved you can simply point the nginx virtual host to the build folder and open homestead.app in the browser, or you can use the serve package via NodeJS:

npm install -g serve
cd build
serve

With serve, your app will be served locally from http://localhost:5000/.

Reddit PWA

You can audit your app without any problems, but in case you want to test it in a mobile device you can also use services like surge.sh to deploy it with one command!

npm install --global surge

Next, run surge from within any directory to publish that directory onto the web.

You can find the hosted version of this app from this link.

Now let’s open Chrome DevTools, go to Audits panel and click on Perform an audit.

Lighthouse report

From the report we can see we already have a score of 45/100 for Progressive Web App and 68/100 for Performance.

Under Progressive Web App we have 6 failed audits and 5 passed audits. That’s because the generated project already has some PWA features added by default, such as a web manifest, a viewport meta and a <no-script> tag.

Under Performance we have diagnostics and different calculated metrics, such as First meaningful paint, First Interactive, Consistently Interactive, Perceptual Speed Index and Estimated Input Latency. We’ll look into these later on.

Lighthouse suggests improving page load performance by reducing the length of Critical Render Chains either by reducing the download size or deferring the download of unnecessary resources.

Please note that the Performance score and metrics values can change between different auditing sessions on the same machine, because they’re affected by many varying conditions such as your current network state and also your current machine state.

Continue reading %Progressive Web Apps: A Crash Course%


Source: Sitepoint