23 Aug 2017, 19:28

Low Hanging PWA Fruit: Manifest Files and Service Worker Precache

It would be a fair assessment to state that Progressive Web Apps (often abbreviated to PWA) are a popular buzzword in the web development and JavaScript communities at the moment. We have also seen further excitement recently, generated by Apple’s move to start supporting development for PWA features within Safari.

Many great posts and documentation exist around explaining the full case for PWAs and how they benefit users. For a solid introduction to Progressive Web Apps check out Google’s page on the matter. In addition, if you’re looking for something tangible there’s also lots of great examples of PWAs that you can explore in more detail at pwa.rocks.

Perhaps now more than ever it’s time to start exploring how you can start looking into aligning your app or site with PWA functionality. This post will be more practical than theoretical, but to give some context I will list out some of the core concepts of what makes a PWA for those of you unfamiliar:

  • Pages are responsive: The app’s content fits in a sensible way on a tablets, mobiles etc
  • Site is served over HTTPS: assets and resources are served using encryption over the wire
  • The entry page loads offline for users
  • The app uses a manifest.json file to allow adding the app to a users homescreen
  • Load times are reasonable even on slower connections like 3G
  • Each page has its own unique URL
  • The site works across modern browsers

Here we will just focus in on two of these concepts and how to integrate them, namely adding a manifest.json file and adding a Service Worker. Subsequently, we can also use the Service Worker to allow the initial page to work offline by using a precache.

Adding a Manifest File

A manifest file provides a few additional weapons to the web app arsenal for developers. The file itself is fairly plain; a JSON file that contains configuration and metadata for various aspects of the application.

However what the manifest file allows for is a whole host of interesting benefits for those looking to give a more ‘app like’ experience:

  • Allowing users to add a web app to their home screen
  • Giving that home screen button a unique name and icon
  • Giving a splash screen to the app when the user loads it
  • Being able to add a theme colour for the web app
  • Define if the app should load ‘standalone’ or in a web browser

Now we’ve gone through why you would add a manifest.json file, let’s take a look at an example config:


{
  "name": "SomeCoolApp",
  "short_name": "SomeCoolApp",
  "start_url": ".",
  "display": "standalone",
  "background_color": "#111111",
  "description": "An app for doing cool things",
   "icons": [{
    "src": "images/manifest/48.png",
    "sizes": "48x48",
    "type": "image/png"
  }, {
    "src": "images/manifest/72.png",
    "sizes": "72x72",
    "type": "image/png"
  }, {
    "src": "images/manifest/96.png",
    "sizes": "96x96",
    "type": "image/png"
  }, {
    "src": "images/manifest/144.png",
    "sizes": "144x144",
    "type": "image/png"
  }, {
    "src": "images/manifest/168.png",
    "sizes": "168x168",
    "type": "image/png"
  }, {
    "src": "images/manifest/homescreen192.png",
    "sizes": "192x192",
    "type": "image/png"
  }],
  "related_applications": [{
    "platform": "web"
  }, {
    "platform": "play",
    "url": "https://play.google.com/store/apps/details?id=SomeCoolApp"
  }]
}

You can see that we provide a name and short_name which give a name and an abbreviated name for the app when space is a premium. start_url expresses where the kick off URL for the application when the user starts the app. For example, it could be their profile page or the home page.

As mentioned, we can decide if the app should load in a web browser or have a more native experience. This is realised through the display property. We can provide standalone to give a more native feel as it hides away browser features like the URL bar (this may be a negative feature depending on your feelings!). There are other options for this such as fullscreen which hides OS UI features, and also minimal-ui which take a middle ground on the matter.

The background_color property allows for us to express a colour that will occur before the app has fully loaded into its container. icons provide a way to give icons for our applications at different device sizes. For a full list of options check out MDN’s page on the matter.

You could write the manifest file manually (see Google’s instructions here). However, if you want a more streamlined experience you could use a generator instead. One generator I found user-friendly and straight forward is the app-manifest app on Firebase, which you can use to generate a zip file which can be unloaded into your web app directory.

Lastly we can include it in our home page’s HTML as so:

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

Adding a Service Worker

The Service Worker is a slightly more complex concept than the manifest file. In essence Service Workers are web workers that allow code to run outside of the web page context within the browser. The Service Worker also in some ways acts as a network proxy, allowing the developer to change the behaviour of network requests (i.e. to read from a cache rather than a remote resource). In principle, these two concepts allow for a host of new opportunities for web apps, including push notifications, offline interactivity and background sync (sending server requests upon resumption of connectivity).

Before we dive in any deeper, it’s important to note that Service Workers require HTTPS to operate, so you will need to have that setup on your site before continuing (checkout Let’s Encrypt if you’re in need of an SSL certificate).

Although we could dig in deep into the Service Worker internals and life cycle, I would rather focus on getting us up and running with a Service Worker. Others have done a great job explaining Service Workers in depth, for example see the Google primer on Service Worker or check out Phil Nash’s great introductory video here. Instead we will focus on one example Service Worker template that allows us to get a registered Service Worker into our page quickly.

An easy to leverage Service Worker template is provided by sw-precache. Using a precache allows you to serve resources from the Service Worker cache, rather than having to wait for it to come over the wire which improves the performance of the app. It also allows us to get resources whilst offline. sw-precache itself is a tool that allows for the automatic code generation of a Service Worker for caching assets that we would normally receive over the network (images, css etc). As sw-precache requires a preprocessing step to generate the Service Worker we need to leverage a task runner. Here we can use gulp, a JavaScript task runner to create a task to generate the list of resources we want to precache. Here’s some example code with comments:


    // Register the service-worker task with Gulp
    gulp.task('service-worker', function(callback) {

        // Get hold of the sw-precache module
        var swPrecache = require('sw-precache');
        var rootDir = '../public/';
        var serviceWorkerName = "precache"; 
        var fileName = `${rootDir}${serviceWorkerName}.js`;

        // Write the precache Service Worker
        swPrecache.write(fileName, {

            // An array of file paths to precache (we use globbing)
            staticFileGlobs: [
                rootDir + 'index.html',
                rootDir + 'templates/.{html}',
                rootDir + 'js/**/*.{js}',
                rootDir + 'css/**/*.{css}',
                rootDir + 'fonts/**/*.{svg,eot,ttf,woff,woff2}',
                rootDir + 'icons/**/*.{svg}',
                rootDir + 'images/**/*.{png,jpg}',
            ],
            // We remove the prefix and can replace it with another
            // Here `../public/` becomes `/` for example
            stripPrexix: rootDir,
            replacePrefix: "/"

        }, callback);

    });

Running gulp service-worker will generate our Service Worker precache file called precache.js. We can now register this into our app using the code expressed below:

    // Check to make sure the Service Worker feature exists
    if ("serviceWorker" in navigator) {
        // On page load, call the Service Worker registration
        window.addEventListener('load', registerSW);
    }

    // The actual registration code
    var registerSW = function() {

        // The location of our generated pre-cache Service Worker
        var swPath = "/precache.js";
        navigator.serviceWorker.register(swPath)
            .then(registrationSuccess, registrationFailed);

    }

    var registrationFailed = function(error) {
        // Do something if there is an error
    }

    var registrationSuccess = function(registration) {
        // Do something if everything is successful
    }

Once the Service Worker is registered the user will make use of the cache when making network requests for cached assets.

Conclusion

Here we have shown how you could add a manifest and a Service Worker to your web app without complicating your application code too much. If you already have gulp in your build process integrating sw-precache shouldn’t be too much extra effort to get up and running. Similarly using the manifest.json app shown above we can simply generate a working manifest file for our application.

Hopefully, this article has begun to pave the way for further PWA features in your applications. Support is gradually getting there so the reasons to avoid the potential benefits are decreasing. If you are interested in auditing your app to see how much it adheres to Google’s PWA checklist, check out a Chrome extension called Lighthouse. Lighthouse will score your app depending on how well it compares a set of pre-defined criteria.

25 Jun 2017, 14:59

Icon Font to SVG Icons: A worked example

There has been an on going discussion about wether Icon Fonts or SVG Icons are ‘better’ for usage on the web. This css-tricks article outlines the introductory differences between the two nicely. The author concludes that “If you can go IE 9+ / Android 3+, inline SVG is better at pretty much everything than icon fonts”. This view has been debated somewhat, with Tyler Sticka laying down a solid case for moving away from Icon Fonts and Ben Frain making a succinct rebuttal. The general consensus within the web development community appears to have been to move over to SVGs however.

One notable benefit I saw for moving to inline SVG was another opportunity to prevent unnecessary render blocking; the process by which content such as CSS/JS/Fonts slow down the rendering path for a page, preventing meaninful content getting to the screen whilst they load.

With this in mind I decided to use my own blog as a way to explore how to make this transition and critically examine any benefits (or problems) it might hold. This post will lay out my approach for swapping out my blogs icon fonts (on the left hand panel, or a the top if you’re on mobile!).

Steps

  1. Remove the icon font CSS

    In this case we were using Font Awesome. Font Awesome is a great resource, and I really admire what they’ve done. Of course however, this post is about removing icon fonts, so out it must go!

        <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
    
  2. Remove the icons themselves

    Here we remove the icons where necessary. In my case I was using 5 icons from an icon font within the sidebar. We simply delete the relevant icons from the HTML, for example the Twitter icon:

        <li class="nav-item">
            <a class="pure-button" href="https://twitter.com/{{ . }}">
                <i class="fa fa-twitter"></i> 
                twitter
            </a>
        </li>
    
  3. Grab the SVG Icons you need

    For the SVG Icons I am choosing to use edent’s SuperTinySocialIcons. These are very efficient SVG icons, covering the majority of your favourite companies/logos. This won’t cover none-social icons (arrows etc) that you might need, in my case I got the cube icon from the The Noun Project and ran it through Jake Archibald’s SVG optimiser. For a more robust approach checkout Sara Soueidan’s superb blog post about using fontello-svg to take Fontello (an aggregator for web fonts) fonts and convert them down to SVG.

  4. Inline the SVG Icons

    You might choose to link out to an external SVG asset, however for performance reasons I have inlined the SVG right into the sidebar, for example:

        <a class="pure-button" href="https://twitter.com/{{ . }}">
        twitter
        <svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
            <rect fill="#1da1f3" height="512" rx="15%" width="512"/>
            <path d="m456 133c-14 7-31 11-47 13 17-10 30-27 37-46-15 10-34 16-52 20-61-62-157-7-141 75-68-3-129-35-169-85-22 37-11 86 26 109-13 0-26-4-37-9 0 39 28 72 65 80-12 3-25 4-37 2 10 33 41 57 77 57-42 30-77 38-122 34 170 111 378-32 359-208 16-11 30-25 41-42z" fill="#fff"/>
        </svg>
        </a>
    
  5. Making necessary edits

    We need to do a little bit of extra work to take the coloured icons and convert them to monochrome. Taking the Twitter icon for example, we can get rid of the rectangle entirely to remove the light blue box:

        <svg class="svg-icons" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
            <path d="m456 133c-14 7-31 11-47 13 17-10 30-27 37-46-15 10-34 16-52 20-61-62-157-7-141 75-68-3-129-35-169-85-22 37-11 86 26 109-13 0-26-4-37-9 0 39 28 72 65 80-12 3-25 4-37 2 10 33 41 57 77 57-42 30-77 38-122 34 170 111 378-32 359-208 16-11 30-25 41-42z" fill="#fff"/>
        </svg>
    
  6. Scale them correctly

    Using a CSS class we can use vertical-align: middle to align the icons vertically and set the width to be in fitting with the adjacent text (16px). We could also just use direct inline CSS if desired.

Outcomes

By default Font Awesome CSS was 5.83Kb over the wire (23.18Kb uncompressed), plus the actual font itself 55.45kb (WOFF2 is compressed). That’s 61.28kb in total, plus two network requests. Using Fontello, I was able to get the font down to 3.17kb (!) by removing all the unused icons. So in total, at it’s most optimised we get down to 9.0kb compressed and two network requests (if uncached).

Inlining the SVGs in the sidebar for the index page takes the HTML page weight up from the original 8.85Kb (compressed) to 9.68Kb (compressed) increasing it by 0.83kb compressed. Using icon fonts in this case eliminated two network requests for render blocking content, and removed 8kb in page weight in the best case and over 60kb in the worst case scenario (using the default Font Awesome CDN CSS link). Lastly, I would say even if you don’t want to make the switch, at least investigate condensing your icon font usage usage down to the icons you use explicitly, using a tool like Fontello.

Things to note: * I didn’t do any scientific experiments on actual page load times (boooo I hear you shout), however there has been some evidence to suggest there are some marginal losses in rendering using SVGs. * IE9+ for support for SVGs (hopefully no longer an issue for 99% of developers) * Similarly older versions of Android lack support (2.3)

17 Jun 2017, 19:28

Deploying a Static Blog with Continuous Integration

In recent years, static sites have seen a resurgence. In this post we’ll explore how to use Hugo, a static site generator, in conjunction with a remote web server and a continuous integration provider. Although the site generation software here is Hugo it could easily be another provider such as Jekyll. The web server will be hosted on a Digital Ocean droplet running Nginx, and CircleCI will be used for for the continuous integration (often abbreviated to simply “CI”). Although it is difficult to speak in specifics due to the multitude of alternatives out there, it should be (hopefully) fairly straightforward to deduce a similar process for other providers.

Firstly, for those of you unfamiliar what Continuous Integration is, here is a definition:

“Continuous Integration is a DevOps software development practice where developers regularly merge their code changes into a central repository, after which automated builds and tests are run” (Amazon Web Services, 2017)

Generally CI is leveraged when there are many developers checking in code to a distributed version control system to ensure the integrity of software before its release to some environment. However we can leverage another one of its key tenets, which is that the building, deployment and testing is being done by a remote service, saving us time and energy. This in turn allows you to focus on writing the blog posts and not how or where the content needs to be deployed.

Some of you may be deploying your static Hugo site (or other static blog) via a bash script or some sort of manual process. This guide will explain how to deploy your blog every single time you commit that code to GitHub, or other cloud based git provider.

Why Bother?

There are a few benefits to setting up CI with your static blog:

  • Avoid repetitive local build and production steps, offload work to another machine
  • Those build steps will always run, so you can’t forget to do them locally (i.e. for theme CSS/JS modification etc)
  • As you need to do it to deploy, it helps you remember to commit your code
  • Clone code to any machine and edit posts from there without worrying about build/deployment dependencies or processes
  • Allows you to edit/create posts using GitHub’s user interface directly
  • Helps keep secrets and sensitive information out of your source code

Setting Up Circle CI and SSH Keys

You will need to register for an account with CircleCI and associate it with your GitHub account. From here you can begin to build GitHub projects from CircleCI. Check out this guide from CircleCI for more specifics regarding that process.

Before we dig into the details, it is important to explain that in order to get the Circle CI talking to our remote server (this case a Digital Ocean droplet), we must setup SSH keys. SSH allows keys allow us to be authenticated by the server whilst avoiding the use of passwords via Public-key cryptography.

It is a little outside the scope of this guide to delve into setting up the keys, however a great guide to generating SSH keys is available from GitHub here, and an explanation of how to use them in conjunction with Circle CI can be found in their docs here. Once you have generated the keys and registered them with CircleCI you can move onto the next section.

Environment Variables

It is desirable to avoid storing any secrets or sensitive information inside the blogs source code itself. One way to do this is to use environment variables on the CI server. CircleCI provides a UI for setting environment in the project settings, on the left hand panel.

For example in this case, the user login password is set as DIGITALOCEAN and the IP of the server is DIGITALOCEAN_IP. This also makes them reusable should you need to use them more than once in your configuration scripts.

The Configuration File

Once our target server and CircleCI are setup with the right keys we can begin to look into how to deploy from CircleCI. With CircleCI we provide a configuration file in the form of ‘circle.yml’. The config is written in YAML which is a minimalist markup language, often used for configs. Here is what my specific circle.yml file looks like:


dependencies:
  pre:
    - wget https://github.com/gohugoio/hugo/releases/download/v0.23/hugo_0.23_Linux-64bit.deb
    - sudo dpkg -i hugo*.deb
    - sudo apt-get install sshpass rsync
    - cd ./themes/impurehugo/ && npm install 

deployment:
  prod:
    branch: master
    commands:
      - cd ./themes/impurehugo/ && npm run build
      - hugo -v
      - sudo sshpass -p "$DIGITALOCEAN" rsync -avz ./public $DIGITALOCEAN_IP:/var/www/html/
      
test:
  override:
    - "true"

You can see in the dependencies section we install hugo at the current latest release (v0.23), and we install the package. We also install sshpass as we will need it to login on the target deployment server.

In my case I do a little extra work with npm and gulp to do some preprocessing (JavaScript/CSS minification, image compression) so we change to the target theme folder and do an npm install there to ge the node dependencies and install gulp. This step can be skipped if you aren’t interested in these preprocessing steps.

With deployment, we pull from master and then we do the frontend pre-processing previously mentioned with gulp compress. After this we run Hugo with the verbose flag (useful for debugging purposes if necessary). Next because Hugo only produces static assets, we can simply move them over to our target server. Here we use rysnc to copy the files to the remote server. rsync has the benefit over scp that it only transfers files that have changed since the last upload. However, you could use something like scp if you are so inclined.

Lastly we override the tests section to simply pass if as our only real major concern is if there are errors in the actual build and deployment steps.

Conclusion

This should hopefully give an overview of how to setup continuous integration with Hugo, and hopefully enough inspiration to adapt it to work with other static site providers if necessary. I really welcome any improvements, requests for clarity of other feedback you might have for me. Feel free to reach out to me on Twitter, or drop me an email.