Your Site without JavaScript

This post was originally published on calibreapp.com and reposted here with the author’s permission. If you’re interested in taking Calibre for a spin, you can start a free 14-day trial today.
There are plenty of reasons why the presence of JavaScript (what it does, how it works, and how heavy it is) needs to be considered a little more thoughtfully.
Web traffic today is made up of more than 50% mobile devices, of these devices, many operate under extremely volatile network connections—loading scripts alone in less than 10 seconds is nigh on impossible in many situations.
If you’re working on a single page app, with no reasonable content-only fallbacks, this can be far more damaging than you may think—users will be watching a white screen, with partial content, for a long time.

According to Google’s DoubleClick, when comparing sites that load in 5 seconds to sites that load in 19 seconds, the faster sites had 70% longer average session lengths, 35% lower bounce rates and 25% higher ad viewability than their slower counterparts.

Performance is important, there’s no doubting that, but what common negative impacts does JavaScript have on our sites? How are we currently evaluating performance?
Let’s Have a Brief (but Constructive) Look at the Cost of JavaScript
When commonly auditing the performance impacts of JavaScript, we look at:

The number of render-blocking scripts present on the page
How long scripts take to download, and the amount of data transferred

But what we’re often missing is what happens thereafter…
Once the device has downloaded the scripts, they must be parsed, converted to bytecode, compiled and then executed.
Parse and compile time are two reasons why the same site that works great on your $3000 MacBook, feels kind of janky on a 2-year-old smartphone.

The above graphic compares Chrome parse/compile times on a regular desktop browser, verses a low power mobile device. This graphic is taken from Addy Osmani’s excellent article titled “JavaScript Start-up Performance".
Ouch.

Let’s say, as an experiment, that we removed all scripts to establish a performance baseline, to answer the question "Just how fast could this be?".
Calibre exists to make it trivial for teams to have better visibility to more areas of performance and user-experience, so in the spirit of that, you can now run a direct comparison of your site with, or without JS—as a Test profile.

💥Now you’re testing with and without JavaScript
I enabled the ability to disable scripts, and run a few test runs against popular global news sites, both with, and without JavaScript.
Continue reading %Your Site without JavaScript%

Link: https://www.sitepoint.com/calibre-your-site-without-javascript/

Building a Multiplayer TicTacToe Game with Meteor

Meteor is a popular, full stack web framework that makes it very easy to prototype your ideas and get from development to production really fast. Its reactive nature and the use of DDP, make it a great candidate for building simple, multiplayer, browser games.
In this tutorial, I’ll show you how to build a multiplayer TicTacToe with Meteor, using its default front-end templating engine, Blaze. I will assume that you have played around with Meteor a bit, and of course, that you feel comfortable coding with JavaScript.

If you have zero experience with Meteor I’d recommend you first follow the TODO app tutorial on the official Meteor site.

You can find the code for the completed app in the accompanying GitHub repo.
Creating the app
If you don’t have Meteor installed you should follow the instructions on their site according to your OS.
Generate the Scaffolding
Now with Meteor installed, open your terminal and run the following command:
meteor create TicTacToe-Tutorial

This will create a folder with the name of your app (in this case TicTacToe-Tutorial). This new folder contains the basic file structure for an app. There’s actually a sample app inside.
Navigate to the folder:
cd TicTacToe-Tutorial

And now run the app:
meteor

I know, I know… that’s a terribly hard-to-remember command, and you’ll be using it a lot, so you should start memorizing it!
If everything went fine now the console should be building the app. After it’s done, open your web browser and go to http://localhost:3000 to see the app running. If you have never done so before, I’d recommend you play around with the sample app. Try to figure out how it works.
Let’s take a look at the file structure. Open your app’s folder. The only things there that we care about (for now) are the client folder and the server folder. The files inside the client folder will be downloaded and executed by the client. The files in the server folder will only be executed on the server and the client has no access to them.
These are the contents in your new folder:
client/main.js # a JavaScript entry point loaded on the client (we won’t be needing this)
client/main.html # an HTML file that defines view templates
client/main.css # a CSS file to define your app’s styles
server/main.js # a JavaScript entry point loaded on the server
package.json # a control file for installing NPM packages
.meteor # internal Meteor files
.gitignore # a control file for git

Building the board
A TicTacToe board is a simple three by three table; nothing too fancy, which is great for our first multiplayer game, so we can focus on the functionality.
The board will be downloaded by the client, so we’ll be editing files inside the client folder. let’s begin by deleting the contents on main.html and replacing it with the following:
client/main.html

<title>tic-tac-toe</title>
</head>

<body>
<table id=”board">
<tr>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
</tr>
<tr>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
</tr>
<tr>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
</tr>
</table>
</body>

Don’t forget to save your files after making changes! Otherwise, they won’t be acknowledged by Meteor.
Now let’s add some css to our board. Open the main.css file and add the following content:
client/main.css
table
{
margin: auto;
font-family: arial;
}

.field
{
height: 200px;
width: 200px;
background-color: lightgrey;
overflow: hidden;
}

#ui
{
text-align: center;
}

#play-btn
{
width: 100px;
height: 50px;
font-size: 25px;
}

.mark
{
text-align: center;
font-size: 150px;
overflow: hidden;
padding: 0px;
margin: 0px;
}

.selectableField
{
text-align: center;
height: 200px;
width: 200px;
padding: 0px;
margin: 0px;
}

We’ve also added a few extra ids and classes that we’ll be using later on in this tutorial.
Finally, delete client/main.js, as we won’t be needing it, and open the app in the browser to see how it looks.
This is fine and all, but is not an optimal solution. Let’s do some refactoring by introducing Blaze Templates.
Creating a Template
Templates are pieces of HTML code with their own functionality that you can reuse anywhere in your app. This is a great way to break up your apps into reusable components.
Before creating our first template, we’ll add two more folders inside the client folder. We’ll call one html and the other one js.
Inside the html folder, create a new board.html file with the following content:
client/html/board.html
<template name="board">
<table id="board">
<tr>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
</tr>
<tr>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
</tr>
<tr>
<td class="field"></td>
<td class="field"></td>
<td class="field"></td>
</tr>
</table>
</template>

Now, on the main.html folder replace the content inside the body tag with the following code:
client/main.html
<head>
<title>tic-tac-toe</title>
</head>

<body>

</body>

This will insert our template with the property name="board", inside the body tag.
But this is the same hard coded board that we had before. Only now, it’s inside a template, so let’s take advantage of the template helpers to build our board dynamically.
Using helpers
We’ll declare a helper in the board template that will provide us with an array with the same length as the dimensions we want our board to have.
inside the js folder create a file called board.js with the following content:
client/js/board.js
import { Meteor } from ‘meteor/meteor’;
import { Template } from ‘meteor/templating’;

Template.board.helpers({
sideLength: () => {
let side = new Array(3);
side.fill(0);

return side;
}
});

Now, we’ll use this helper in the board’s template HTML to repeat one single row for each element in the array provided by the helper. To help us with this, we’ll use the Each-in Spacebars block helper.
Replace the content inside the board.html file with the following:
client/html/board.html
<template name="board">
<table id="board">

<tr>

<td class="field" id="">

</td>

</tr>

</table>
</template>

Notice that we’re looping through the array twice, once for the rows and once for the columns, instantiating the corresponding tag (tr or td) as we go. We’re also setting their id properties as the @index of the row + @index of the column. What we get is a two digits number that will help us identify that element, with its position on the board.
Check out the app at http://localhost:3000 to see how it’s looking so far.
UI
Now that we have a good looking board, we’ll need a play button and a tag to show information on the current game.
Let’s begin by creating the ui.html file inside the html folder… you know the drill. Now, add the following content to it:
client/html/ui.html
<template name ="ui">
<div id="ui">

<p id="status">

</p>

<button id="play-btn">Play</button>

</div>
</template>

As you can see we’re using the #if Spacebars block helper and the inGame helper (that we haven’t yet defined) as a condition. There’s the status helper inside the p tag too. We’ll define that later also.
How does it work? #if the inGame helper returns true, the player will see whatever’s in the status helper. Otherwise, we’ll simply show the play button.
Don’t forget, for this component to be displayed we need to add it to our main client template:
client/main.html
<head>
<title>tic-tac-toe</title>
</head>

<body>

</body>

Logging in
We won’t be dealing with any login UI. We will install a very useful package called brettle:accounts-anonymous-auto that will automatically log in all users anonymously into our app.
Head over to your console and run the following command:
meteor add brettle:accounts-anonymous-auto

Now, when you open the app for the first time after adding this package, it’ll create a new user, and every time you open the app on the same browser it’ll remember you. If we’re not keeping any data from said user, it might be better to just remove them when they log out. But we’re not going over that in this tutorial.
Building the Game
Finally, we’re going to start building the game itself! Let’s go over the functionality we’ll be implementing, to have a clear view of what’s coming next.
We’ll need functionality for:
Continue reading %Building a Multiplayer TicTacToe Game with Meteor%

Link: https://www.sitepoint.com/building-multiplayer-tictactoe-game-with-meteor/

How to Create a QR Code Reader for Your Mobile Website

The barcode and QR code have modernized our shopping and searching experience. Customers carrying smartphones can now pick up a product anywhere in the world, scan its barcode or its QR code using one of the many free phone apps and find out its lowest price as well as where it can be bought.

Companies like Walmart and Amazon have embraced this technique to draw customers to their online and offline stores using their phone app. Other companies like Fedex and UPS allow customers to scan the codes on packages using a phone app, instead of needing to manually type in long lists of characters.
If the users of your mobile website have a need to type in long codes like activation codes or they like to look up specific products on your website based on a model number printed in a magazine or advertisement, then you too can take advantage of QR codes to eliminate the frustration of tiny keyboards and spare them the need to double check for errors.
QR Code Scanning with your Mobile Website
You don’t need a native phone app to scan QR codes —it’s quite simple to create your own QR code reader. Your website running on a smartphone equipped with a camera and running a little JavaScript can do the same trick.
Here is a demo of a text field with an in-built QR button. In addition to being able to type text into the field, users can also click a button to activate the camera.

Browser Requirements:
Your users need to be on an iPhone running iOS 6 or higher or an Android phone running Android 3.0 or higher. Other devices have not been tested.

See the Pen Bare QR reader demo by SitePoint (@SitePoint) on CodePen.

If you are on a supported device, go ahead and click it. Depending on your phone, it will either launch the camera immediately or ask you whether to open the camera or browse your photo library. On unsupported devices, the browser will open up a regular file explorer window.
If you don’t have a QR code handy to scan, here is one that shows the first 8 digits of Pi.

Creating the QR Code Reader
The magic starts with the file upload element. We spruce it up with an accept attribute which tells the browser that we only want images and we give it a capture attribute which means we want the input to be captured now, as opposed to uploading an old picture from the phone’s memory.

Link: https://www.sitepoint.com/create-qr-code-reader-mobile-website/

Quick Tip: Getting Started with Headless Chrome in Node.js

Oftentimes in our line of work we need to be able to replicate a user journey repeatedly to make sure that our pages are offering a consistent experience as we make changes to our site. Critical to being able to accomplish this consistently and conveniently are libraries that allow us to script these types of tests, so that we can run assertions against them and maintain documentation around the results. Enter headless browsers: command line tools that provide you with the ability to script a user’s interactions across your site programmatically and capture the results to use in tests.
Many of us have been using PhantomJS, CasperJS, and other tools for years to do just this. But, as often is with love, our hearts can be bequeathed to another. As of Chrome 59 (60 for Windows users), Chrome ships with its own headless browser. And, although it doesn’t currently offer support for Selenium, it uses Chromium and the Blink engine, i.e. it is simulating an actual user experience in Chrome.
As ever, the code for this article can be found on our GitHub repo.
Run Headless Chrome From the Command Line
Running Headless Chrome from the command line is relatively easy. On a Mac, you can set an alias for Chrome and run using the —headless command line parameter
alias chrome=”/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome”
chrome –headless –disable-gpu –remote-debugging-port=9090 https://www.sitepoint.com/

On Linux, it’s even easier:
google-chrome –headless –disable-gpu –remote-debugging-port=9090 https://www.sitepoint.com/

–headless: Runs without a UI or display server dependencies
–disable-gpu: Disables GPU hardware acceleration. This is temporarily needed for now.
–remote-debugging-port: Enables remote debug over HTTP on the specified port.

You can also interact with the page you are requesting, for example to print document.body.innerHTML to stdout you can do:
google-chrome –headless –disable-gpu –dump-dom http://endless.horse/

If you’re curious what else is possible, a full list of parameters can be found here.
Running Headless Chrome in Node.js
The focus of this article however, is not the command line, rather running Headless Chrome in Node.js. To do this, we’re going to need the following modules:

chrome-remote-interface: JavaScript API provides a simple abstraction of commands and notifications.
chrome-launcher: this allows us to launch Chrome from within Node across multiple platforms.

Continue reading %Quick Tip: Getting Started with Headless Chrome in Node.js%

Link: https://www.sitepoint.com/headless-chrome-node-js/

Nuxt.js: A Universal Vue.js Application Framework

Universal (or Isomorphic) JavaScript is a term that has become very common in the JavaScript community. It is used to describe JavaScript code that can execute both on the client and the server.
Many modern JavaScript frameworks, like Vue.js, are aimed at building Single Page Applications (SPAs). This is done to improve the user experience and make the app seem faster since users can see updates to pages instantaneously. While this has a lot of advantages, it also has a couple of disadvantages, such as long “time to content" when initially loading the app as the browser retrieves the JavaScript bundle, and some search engine web crawlers or social network robots will not see the entire loaded app when they crawl your web pages.
Server-side Rendering of JavaScript is about preloading JavaScript applications on a web server and sending rendered HTML as the response to a browser request for a page.
Building Server-side rendered JavaScript apps can be a bit tedious, as a lot of configuration needs to be done before you even start coding. This is the problem Nuxt.js aims to solve for Vue.js applications.
What is Nuxt.js
Simply put, Nuxt.js is a framework that helps you build Server Rendered Vue.js applications easily. It abstracts most of the complex configuration involved in managing things like asynchronous data, middleware, and routing. It is similar to Angular Universal for Angular, and Next.js for React.
According to the Nuxt.js docs "its main scope is UI rendering while abstracting away the client/server distribution."
Static Generation
Another great feature of Nuxt.js is its ability to generate static websites with the generate command. It is pretty cool and provides features similar to popular static generation tools like Jekyll.
Under the Hood of Nuxt.js
In addition to Vue.js 2.0, Nuxt.js includes the following: Vue-Router, Vue-Meta and Vuex (only included when using the store option). This is great, as it takes away the burden of manually including and configuring different libraries needed for developing a Server Rendered Vue.js application. Nuxt.js does all this out of the box, while still maintaining a total size of 28kb min+gzip (31kb with vuex).
Nuxt.js also uses Webpack with vue-loader and babel-loader to bundle, code-split and minify code.
How it works
This is what happens when a user visits a Nuxt.js app or navigates to one of its pages via :

When the user initially visits the app, if the nuxtServerInit action is defined in the store, Nuxt.js will call it and update the store.
Next, it executes any existing middleware for the page being visited. Nuxt checks the nuxt.config.js file first for global middleware, then checks the matching layout file (for the requested page), and finally checks the page and its children for middleware — middleware are prioritized in that order.
If the route being visited is a dynamic route, and a validate() method exists for it, the route is validated.
Then, Nuxt.js calls the asyncData() and fetch() methods to load data before rendering the page. The asyncData() method is used for fetching data and rendering it on the server-side, while the fetch() method is used to fill the store before rendering the page.
At the final step, the page (containing all the proper data) is rendered.

These actions are portrayed properly in this schema, gotten from the Nuxt docs:

Creating A Serverless Static Site With Nuxt.js
Let’s get our hands dirty with some code and create a simple static generated blog with Nuxt.js. We will assume our posts are fetched from an API and will mock the response with a static JSON file.
To follow along properly, a working knowledge of Vue.js is needed. You can check out Jack Franklin’s great getting started guide for Vue.js 2.0 if you’re a newbie to the framework. I will also be using ES6 Syntax, and you can get a refresher on that here: https://www.sitepoint.com/tag/es6/.
Our final app will look like this:

The entire code for this article can be seen here on GitHub, and you can check out the demo here.
Application Setup and Configuration
The easiest way to get started with Nuxt.js is to use the template created by the Nuxt team. We can install it to our project (ssr-blog) quickly with vue-cli:
vue init nuxt/starter ssr-blog

Note: If you don’t have vue-cli installed, you have to run npm install -g vue-cli first, to install it.

Next, we install the project’s dependencies:
cd ssr-blog
npm install

Now we can launch the app:
npm run dev

If all goes well, you should be able to visit http://localhost:3000 to see the Nuxt.js template starter page. You can even view the page’s source, to see that all content generated on the page was rendered on the server and sent as HTML to the browser.
Next, we can do some simple configuration in the nuxt.config.js file. We will add a few options:
// ./nuxt.config.js

module.exports = {
/*
* Headers of the page
*/
head: {
titleTemplate: ‘%s | Awesome JS SSR Blog’,
// …
link: [
// …
{
rel: ‘stylesheet’,
href: ‘https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.2/css/bulma.min.css’
}
]
},
// …
}

In the above config file, we simply specify the title template to be used for the application via the titleTemplate option. Setting the title option in the individual pages or layouts will inject the title value into the %s placeholder in titleTemplate before being rendered.
We also pulled in my current CSS framework of choice, Bulma, to take advantage of some preset styling. This was done via the link option.

Note: Nuxt.js uses vue-meta to update the headers and HTML attributes of our apps. So you can take a look at it for a better understanding of how the headers are being set.

Now we can take the next couple of step by adding our blog’s pages and functionalities.
Working with Page Layouts
First, we will define a custom base layout for all our pages. We can extend the main Nuxt.js layout by updating the layouts/default.vue file:
Continue reading %Nuxt.js: A Universal Vue.js Application Framework%

Link: https://www.sitepoint.com/nuxt-js-universal-vue-js/

Using Polymer in WordPress: Build a Custom Google Maps Component

Web components are a set of standards for creating custom, reusable HTML elements. Polymer is an open-source JavaScript library for building web applications using web components. Created by those clever folks at Google, it provides a number of additional features over vanilla web components and when used with a polyfill, supports the latest version of all major browsers.
In this tutorial I’m going to show you how easy it is to make use of web components and Polymer in WordPress. I’m going to start by showing you how to integrate Polymer into your WordPress install, then I’m going to demonstrate how to add a working Google Maps component to your site’s side bar. This might be useful for any site (e.g. that of a restaurant) which needs to provide visitors with directions to their premises.
After reading, you’ll be able to employ this technique on a site of your own. And you’ll not be limited to a Google Map widget, you’ll be able to choose from the wide range of pre-made components, or even write your own.
As ever, all of the code for this tutorial is available in a GitHub repository.
Why Polymer?
As native support for web components is growing ever better, you might be forgiven for asking if Polymer is still relevant. The short answer to that question is Yes!
Polymer does make use of a variety of web component polyfills—which will hopefully one day full by the wayside—but it is a lot more than that. Polymer is a wrapper around the web components API that allows us to develop and implement new components at a much greater speed than we would otherwise be able. It offers various additional features over vanilla web components, such as one-way and two-way data binding, computed properties and gesture events. It comes with a very polished CLI which can be used for such tasks as scaffolding out a project, running tests, or running a local server, and it can make use of a wide range of pre-built elements, such as the much loved material design elements library.
In short, Polymer is still very relevant. It is a powerful framework, which is used in production by large companies such as USA Today, Coca Cola and Electronic Arts.
Setting Up WordPress
Before we start, we need to setup our environment that is going to be running WordPress. For this tutorial, I’ll be using the ScotchBox Vagrant VM, equipped with some pre-installed tools to kickstart your WordPress installation.

If you have WordPress installed already, or would prefer to use a different method, you can skip this bit. If you need a bit of help with the setup, but don’t want to go the vagrant route described below, try Googling “install WordPress locally" and looking for an up-to-date tutorial.

We start of by making sure that Git, Vagrant and Virtual Box are installed on our system. We can then clone the GitHub repo with ScotchBox’s pre-populated Vagrantfile.
git clone https://github.com/scotch-io/scotch-box sitepoint-wp-polymer

Now we are ready to run vagrant up. After our machine has booted, we have to remove the default /public/index.php static file and install WordPress.
cd sitepoint-wp-polymer/public
rm index.php
git clone https://github.com/WordPress/WordPress.git .

Now we have to make a duplicate of the wp-config-sample.php file. Name it wp-config.php.
cp wp-config-sample.php wp-config.php

and edit the following values:
// wp-config.php

// …

define(‘DB_NAME’, ‘scotchbox’);
define(‘DB_USER’, ‘root’);
define(‘DB_PASSWORD’, ‘root’);

// …

Now you are ready to fire up your browser and visit http://192.168.33.10. You will be prompted to enter the admin account credentials and site title. Feel free to fill these out as you see fit.

Adding the SitePoint Base Theme
So we’ve got WordPress set up, now we need a theme. Out of the box, this will be the Twenty Seventeen theme, but this is pretty generic and includes much more than you normally need. A good alternative here, is to use the SitePoint WordPress base theme.
This theme was created in response to the question "What would the perfect WordPress base theme look like?". Its features include:

No fat. No cruft. Speedy.
Minimal design. It’s your job to make it pretty.
No ‘cute’ features you never actually use.
SEO friendly to its core.
Super Mobile-friendly.
100% Open Source and free to use.

The SitePoint WordPress base theme is a great starting point for new projects. It’s mobile friendly, easy to use and 100% free. To follow along with the rest of tis tutorial, head over to the theme’s homepage and download it now.
And while you’re there, you might like to check out the suite of paid themes SitePoint offers, too. These are all built on top of the base theme and include an ecommerce theme, restaurant theme, portfolio theme, business theme and construction theme.
After downloading SitePoint WordPress base theme, unzip it and copy/paste to thewp-content/themes folder. Then create a new folder called sitepoint-base-child, in wp-content/themes. In that directory create a style.css file and a functions.php file.
cd wp-content/themes/
mkdir sitepoint-base-child
cd sitepoint-base-child
touch functions.php style.css

Open up style.css and copy this into it:
/*
Theme Name: SitePoint Base Child
Author: Almir B.
Author URI: http://almirbijedic.rocks
Template: sitepoint-base
Version: 1.0.0
Text Domain: ab-sitepoint-base
*/

And into functions.php:
Themes from the main side menu, and click Activate under, Sitepoint Base Child theme.

Including Polymer in WordPress
Now that’s done, we have to install Polymer with bower. Make sure you are in the public/wp-content/themes/sitepoint-base-child folder, and then run:
bower init

You can answer with default answer to every question. Next we need to install the dependencies:
bower install –save Polymer/polymer#^2.0.0 PolymerElements/paper-input#2.0-preview

This will install Polymer and the paper-input component, so that we can have a fancy material designed input component out of the box. It is important to use the #2.0-preview tag for the paper input and also for the Google Map element later, as it will not work with the latest version of Polymer (version 2.0) otherwise.
In order to user Polymer, we have to include it using an HTML import, and we will also include the polyfill for web components, so as to support older browsers.
Head to the functions.php file in the child theme, and add an enqueue to the existing enqueue function.
<?php
//functions.php

add_action( ‘wp_enqueue_scripts’, ‘sp_theme_enqueue_styles’ );
function sp_theme_enqueue_styles() {
wp_enqueue_style( ‘parent-style’, get_template_directory_uri() . ‘/style.css’ );
wp_enqueue_script( ‘polymer’, get_stylesheet_directory_uri() . ‘/bower_components/webcomponentsjs/webcomponents-lite.js’ );
}

WordPress does not have an enqueue function for enqueueing HTML imports, but we can hook into the wp_head hook which outputs into the <head> element of the page.
<?php
//functions.php

add_action( ‘wp_enqueue_scripts’, ‘sp_theme_enqueue_styles’ );
function sp_theme_enqueue_styles() {
wp_enqueue_style( ‘parent-style’, get_template_directory_uri() . ‘/style.css’ );
wp_enqueue_style( ‘polymer’, get_stylesheet_directory_uri() . ‘/bower_components/webcomponentsjs/webcomponents-lite.min.js’ );
}

add_action( ‘wp_head’, ‘include_polymer_elements’ );
function include_polymer_elements() {
?>

<link rel="import"
href="<?php echo get_stylesheet_directory_uri() ?>/bower_components/polymer/polymer.html">
<link rel="import"
href="<?php echo get_stylesheet_directory_uri() ?>/bower_components/paper-input/paper-input.html">
<?php
}

That’s all we needed to start using Polymer elements in WordPress. Now let’s create a WordPress widget so we can take this out for a test ride.
Registering a Widget
In order to create a new widget, we will create a new child class from the WP_Widget class and then register it with the widgets_init hook.
Create a new folder in your child theme, name it lib, and add it a file named sitepoint-map-widget.php.
mkdir lib
cd lib
touch sitepoint-map-widget.php

Copy the following into that file:
<?php
// lib/sitepoint-map-widget.php

class SitepointMapWidget extends WP_Widget {

function __construct() {
// Instantiate the parent object
parent::__construct( false, ‘Google Paper Input’ );
}

function widget( $args, $instance ) {
echo ‘<paper-input raised always-float-label label="Floating label"></paper-input>’;
}
}

All we did here is create a new child class of WP_Widet and called the parent constructor in order to give the widget a custom name. Additionally, the widget function is the one that does the actual output. For now, we will simply output a <paper-input> element, which is an element from the paper-input-elements collection.
Last but not least, we need to include this new PHP file at the top of our functions.php file:
<?php
// functions.php
require_once( ‘lib/sitepoint-map-widget.php’ );

// …

and then register a widget at the end of the file:
<?php
// functions.php

// …

add_action( ‘widgets_init’, ‘sp_register_widgets’ );
function sp_register_widgets() {
register_widget( ‘SitepointMapWidget’ );
}

Now we can go into the admin dashboard of WordPress. From the main menu, go into Appearance > Widgets, and there you should see a widget named Google Paper Input on the left.
Drag and drop it into the Main Sidebar section to the right, above the rest of the default widgets from the SitePoint Base theme.

Now you can visit the homepage, and on the right side right above the search box, you will see a material design input with a label.

And thus we have concluded Polymer’s Hello, World! example. We’ve covered a lot of ground already—installing Polymer, integrating it with WordPress and including a sample widget, all in just a few lines of code—but in the next section we will take this further and implement our Google Map component.
Continue reading %Using Polymer in WordPress: Build a Custom Google Maps Component%

Link: https://www.sitepoint.com/polymer-wordpress-custom-component/

Creating Beautiful Charts Using Vue.js Wrappers for Chart.js

Charts are an important part of modern websites and applications. They help to present information that cannot be simply represented in text. Charts also help to make sense of data that would ordinarily not make sense in a textual format by presenting them in a view that’s easy to read and understand.
In this article I will show you how to represent data in the form of various types of chart with the help of Chart.js and Vue.js.
Chart.js is a simple yet flexible JavaScript charting library for developers and designers that allows drawing of different kinds of chart by using the HTML5 canvas element. A good refresher on Chart.js can be read here.
Vue.js is a progressive JavaScript framework, which we’ll use alongside Chart.js to demonstrate the chart examples. There’s an awesome primer on using Vue.js on Sitepoint and that can be read here. We’ll also be using vue-cli to scaffold a Vue.js project for the demo we are going to build. vue-cli is a simple CLI for scaffolding Vue.js projects. It offers various templates from which an app can be built, but we will be using the webpack template to bootstrap our app.
Charts, Charts, Charts
There are different types of JavaScript charting libraries and various chart wrappers built on Vue.js, but as we are focused on Chart.js in this article, we will be looking at Vue wrappers for Chart.js.
There is an awesome collection of Vue wrappers for charts on the awesome-vue repo on GitHub but we are only interested in the following Chart.js wrappers:

vue-charts
vue-chartjs
vue-chartkick

We will be using the various wrappers to demonstrate how to create different types of chart and also touch on the unique features that each of these wrappers possesses.
Scaffolding the Project with vue-cli
Let’s get started by installing vue-cli with the following command:
npm install -g vue-cli

Once that’s done, we can then get started with scaffolding a project by typing in:
vue init webpack my-project

We are specifying that we want a Vue.js app created for us with the webpack template and the name of the project as my-project. Respond to all of the questions and let vue-cli do the rest of the magic. Awesome!
Now let us go ahead to install the dependencies and Chart.js wrappers needed for our app:
npm install chart.js chartkick hchs-vue-charts vue-chartjs vue-chartkick

Tip: If you use npm 5, no need for the –save flag anymore as all packages are automatically saved now. Read more about that here.

This will install all the dependencies and Chart.js Vue wrappers needed. Let’s test what we have so far and run our application and see if the app was successfully created. According to the vue-cli docs, running npm run dev will create a first-in-class development experience in which we can interact and engage with our app. So let’s do that.
npm run dev

You can visit localhost:8080 in your browser to see the welcome page.
Adding Routes
Next thing we want to do is create the different routes in which we can view the charts for each of the wrappers above. At the end, we would like to have a /charts route to display charts made with the vue-charts wrapper, /chartjs to display charts made with the vue-chartjs wrapper, and lastly /chartkick to display charts made with the vue-chartkick wrapper.
Navigate to the router folder of the app and open up theindex.js file. Let’s replace the content of that file with this:
import Vue from ‘vue’ // Import Vue from node_modules
import Router from ‘vue-router’ // Import Vue Router from node_modules
import Home from ‘@/components/Home’ //The Home component that’s in charge of everything we see on the app’s homepage
import VueChartJS from ‘@/components/VueChartJS’ //The VueChartJS component that displays the vue-chartjs charts.
import VueChartKick from ‘@/components/VueChartKick’ //The VueChartJS component that displays the vue-chartkick charts.
import VueCharts from ‘@/components/VueCharts’ //The VueChartJS component that displays the vue-charts charts.

//Specify that we want to use Vue Router
Vue.use(Router)

export default new Router({
routes: [
{
path: ‘/’,
name: ‘Home’,
component: Home
},
{
path: ‘/chartjs’,
name: ‘VueChartJS’,
component: VueChartJS
},
{
path: ‘/chartkick’,
name: ‘VueChartKick’,
component: VueChartKick
},
{
path: ‘/charts’,
name: ‘VueCharts’,
component: VueCharts
}
]
})

Before we discuss the code above, make sure to create the files below in the src/components/ folder. This is done so that the routes defined above have their own component.

VueChartJS.vue
VueChartKick.vue
VueCharts.vue

So what’s happening in the code block above?
We imported some files which are the Vue components that we created above. Components are one of the most powerful features of Vue. They help us extend basic HTML elements to encapsulate reusable code. At a high level, components are custom elements that Vue’s compiler attaches behavior to.
Lastly, we defined the routes and components which will serve the different pages we need to display the different charts.
Home Component
As mentioned above, the Home component serves as the default (/) route and we will need to create it. We can do that, or simply rename the existing Hello.vue file to Home.vue and replace the content with the code block below.