Production Ready Polymer - UI

In production, it becomes important to make the responses quick and the pages to load within tens of milli seconds. A polymer based page definitely makes more network calls than a regular html page. To solve this problem, we can use polymer-build.

According to Polymer-Build , The Polymer CLI uses polymer-build under the hood, so you can think of the CLI’s build command like running a pre-configured polymer-build pipeline.

While polymer-build can be run as a part of polymer cli, it is built on Node.js streams and more specifically to work easily with Gulp.

Some of the tips to make html pages load faster is given below:

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Author_fast-loading_HTML_pages

While https://www.polymer-project.org/1.0/docs/tools/optimize-for-production polymer suggests vulcanization and crisper, there are about other tasks like minify, uglify,lazy load and cssSlam which all together achieves our performance goals for production.

You can learn all about polymer-build here

What needs to be done in oe-ui

For, ui-routes, add a “!” before the name of the ui-route, so the minification, does not effect the load of elements.

for example

 {
        "type": "elem",
        "name": "!create-product",
        "path": "/Product",
        "import": "src/create-product.html",
        "transitions": [{
            "path": "/product-list",
            "route": "/product-list",
            "event": "oe-formdata-inserted"
        }],
        "scope": {
            "roles": ["admin"]
        }
    }

Add the below script in index.html as below : Also, remove, imports of polymer and webcomponent-lite as they are added in the below script

//this is the modified section
    <script>
        // Setup Polymer options
        window.Polymer = {
            dom: 'shadow',
            lazyRegister: true,
        };

        /**
         * [polymer-root-path]
         *
         * By default, we set `Polymer.rootPath` to the server root path (`/`).
         * Leave this line unchanged if you intend to serve your app from the root
         * path (e.g., with URLs like `my.domain/` and `my.domain/view1`).
         *
         * If you intend to serve your app from a non-root path (e.g., with URLs
         * like `my.domain/my-app/` and `my.domain/my-app/view1`), edit this line
         * to indicate the path from which you'll be serving, including leading
         * and trailing slashes (e.g., `/my-app/`).
         */
        window.Polymer.rootPath = '/';

        // Load webcomponentsjs polyfill if browser does not support native
        // Web Components
        (function() {
            'use strict';

            var onload = function() {
                // For native Imports, manually fire WebComponentsReady so user code
                // can use the same code path for native and polyfill'd imports.
                if (!window.HTMLImports) {
                    document.dispatchEvent(
                        new CustomEvent('WebComponentsReady', {
                            bubbles: true
                        })
                    );
                }
            };

            var webComponentsSupported = (
                'registerElement' in document &&
                'import' in document.createElement('link') &&
                'content' in document.createElement('template')
            );

            if (!webComponentsSupported) {
                var script = document.createElement('script');
                script.async = true;
                script.src =
                    'bower_components/webcomponentsjs/webcomponents-lite.min.js';
                script.onload = onload;
                document.head.appendChild(script);
            } else {
                onload();
            }
        })();
    </script>

    

Add polymer.json to the project folder, description of each property of polymer.json can be found here.Here is a sample for you.

{
   
    "entrypoint": "client/index.html",
    
    "shell": "client/src/oe-app.html",

    "fragments": [
        "client/src/create-product.html",
        "client/src/product-list.html",
        "client/src/product-form.html",
        "client/src/user-profile.html"
    ],
    "sources": [
        "client/src/**/*",
        "client/images/**/*",
        "bower.json"
    ],
    "extraDependencies": [
        "client/bower_components/webcomponentsjs/webcomponents-lite.min.js"
    ],
    "lint": {
        "rules": ["polymer-1"]
    },
    "builds": [{
            "preset": "es5-bundled"
        },
        {
            "preset": "es6-bundled"
        },
        {
            "preset": "es6-unbundled"
        }
    ]
}

While, these are done, along with the gulpfile as below, you can additionally add many tasks to the gulp file, you can find them here

'use strict';

const del = require('del');
const gulp = require('gulp');
const gulpif = require('gulp-if');
const mergeStream = require('merge-stream');
const polymerBuild = require('polymer-build');

// Here we add tools that will be used to process our source files.
const imagemin = require('gulp-imagemin');

// Additional plugins can be used to optimize your source files after splitting.
// Before using each plugin, install with `npm i --save-dev <package-name>`
// const uglify = require('gulp-uglify');
// const cssSlam = require('css-slam').gulp;
// const htmlMinifier = require('gulp-html-minifier');

const polymerJson = require('./polymer.json');
const polymerProject = new polymerBuild.PolymerProject(polymerJson);
const buildDirectory = 'build';

/**
 * Waits for the given ReadableStream
 */
function waitFor(stream) {
    return new Promise((resolve, reject) => {
        stream.on('end', resolve);
        stream.on('error', reject);
    });
}

function build() {
    return new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars

        // Lets create some inline code splitters in case you need them later in your build.
        let sourcesStreamSplitter = new polymerBuild.HtmlSplitter();
        let dependenciesStreamSplitter = new polymerBuild.HtmlSplitter();

        // Okay, so first thing we do is clear the build directory
        console.log(`Deleting ${buildDirectory} directory...`);
        del([buildDirectory])
            .then(() => {

                // Let's start by getting your source files. These are all the files
                // in your `src/` directory, or those that match your polymer.json
                // "sources"  property if you provided one.
                let sourcesStream = polymerProject.sources()

                // If you want to optimize, minify, compile, or otherwise process
                // any of your source code for production, you can do so here before
                // merging your sources and dependencies together.
                .pipe(gulpif(/\.(png|gif|jpg|svg)$/, imagemin()))

                // The `sourcesStreamSplitter` created above can be added here to
                // pull any inline styles and scripts out of their HTML files and
                // into seperate CSS and JS files in the build stream. Just be sure
                // to rejoin those files with the `.rejoin()` method when you're done.
                .pipe(sourcesStreamSplitter.split())

                // Uncomment these lines to add a few more example optimizations to your
                // source files, but these are not included by default. For installation, see
                // the require statements at the beginning.
                // .pipe(gulpif(/\.js$/, uglify())) // Install gulp-uglify to use
                // .pipe(gulpif(/\.css$/, cssSlam())) // Install css-slam to use
                // .pipe(gulpif(/\.html$/, htmlMinifier())) // Install gulp-html-minifier to use

                // Remember, you need to rejoin any split inline code when you're done.
                .pipe(sourcesStreamSplitter.rejoin());


                // Similarly, you can get your dependencies seperately and perform
                // any dependency-only optimizations here as well.
                let dependenciesStream = polymerProject.dependencies()
                    .pipe(dependenciesStreamSplitter.split())
                    // Add any dependency optimizations here.
                    .pipe(dependenciesStreamSplitter.rejoin());


                // Okay, now let's merge your sources & dependencies together into a single build stream.
                let buildStream = mergeStream(sourcesStream, dependenciesStream)
                    .once('data', () => {
                        console.log('Analyzing build dependencies...');
                    });

                // If you want bundling, pass the stream to polymerProject.bundler.
                // This will bundle dependencies into your fragments so you can lazy
                // load them.
                buildStream = buildStream.pipe(polymerProject.bundler());

                // Now let's generate the HTTP/2 Push Manifest
                buildStream = buildStream.pipe(polymerProject.addPushManifest());

                // Okay, time to pipe to the build directory
                buildStream = buildStream.pipe(gulp.dest(buildDirectory));

                // waitFor the buildStream to complete
                return waitFor(buildStream);
            })
            .then(() => {
                // You did it!
                console.log('Build complete!');
                resolve();
            });
    });
}

gulp.task('build', build);

You can add a build task to the git or any CI, CD that you use, and there you are done, with adding performance optimization and making your application , production ready.

PS: In addition to above,you can add Offline caching with Service Worker Precache

Summary

Polymer-Build can be used, to make application UI production ready.