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/

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/

JavaScript Design Patterns: The Observer Pattern

In JavaScript, there is a problem that comes up often. You need a way to update parts of a page in response to certain events, with the data these provide. Say, for example, user input that you then project into one or many components. This leads into a lot of push-and-pull in the code to keep everything in sync.
This is where the observer design pattern can help — it enables one-to-many data binding between elements. This one-way data binding can be event driven. With this pattern, you can build reusable code that solves for your specific needs.
In this article, I’d like to explore the observer design pattern. It will help you solve a common problem you see in client-side scripting. That is one-to-many, one-way, and event-driven data binding. It is a problem that comes up often when you have many elements that must be in sync.
I’ll use ECMAScript 6 to illustrate the pattern. Yes, there will be classes, arrow functions, and constants. Feel free to explore these topics on your own if you are not already familiar. I’ll use parts of ES6 that introduce syntactic sugar only, so it is portable with ES5 if need be.
And I’ll use Test-Driven-Development (TDD) to work on the pattern. This way you have a way knowing how each component is useful.
The new language features in ES6 make for some succinct code. So, let’s get started.
The Event Observer
A high-level view of the pattern looks like this:
EventObserver

├── subscribe: adds new observable events

├── unsubscribe: removes observable events
|
└── broadcast: executes all events with bound data

After I flesh out the observer pattern I’ll add a word count that uses it. The word count component will take this observer and bring it all together.
To initialize the EventObserver do:
class EventObserver {
constructor() {
this.observers = [];
}
}

Start with an empty list of observed events, and do this for every new instance. From now on, let’s add more methods inside EventObserver to flesh out the design pattern.
The Subscribe Method
To add new events do:
subscribe(fn) {
this.observers.push(fn);
}

Grab the list of observed events and push a new item to the array. The list of events is a list of callback functions.
One way to test this method in plain JavaScript is as follows:
// Arrange
const observer = new EventObserver();
const fn = () => {};

// Act
observer.subscribe(fn);

// Assert
assert.strictEqual(observer.observers.length, 1);

I use Node assertions to test this component in Node. The exact same assertions exist as Chai assertions too.
Note the list of observed events consists of humble callbacks. We then check the length of the list and assert that the callback is on the list.
The Unsubscribe Method
To remove events do:
unsubscribe(fn) {
this.observers = this.observers.filter((subscriber) => subscriber !== fn);
}

Continue reading %JavaScript Design Patterns: The Observer Pattern%

Link: https://www.sitepoint.com/javascript-design-patterns-observer-pattern/

Grab Our Free Printable Functional JavaScript Cheat Sheet

Functional programming (FP) has become a hot topic in the JavaScript community. It’s being touted as a great way of building scalable and maintainable applications and we’re staring to see many of its core principles incorporated into libraries and frameworks — for example stateless functional components in React.
Continue reading %Grab Our Free Printable Functional JavaScript Cheat Sheet%

Link: https://www.sitepoint.com/grab-free-printable-functional-javascript-cheat-sheet/

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/

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/

A Beginner’s Guide to HTML5 Cross-Browser Polyfills

The web can seem fast moving. New frameworks, tools, and even languages come and go. Yet many developers feel that they have to move as fast as their slowest user. New browsers are ‘evergreen’ — they auto-update unseen in the background without asking for permission, and they’re making leaps and bounds in terms of progressing new APIs.
Yet even modern browsers implement features at different times. It’s frustrating to read about the bleeding-edge of modern development only to think it’s all unusable for years to come. Maybe you’ve looked through your site’s analytics and spotted users still on IE9? Should you code like it’s 2011 or delegate everything to jQuery or some framework? There is another option. Enter the polyfill.
What Are Polyfills and Why Do We Need Them?
Remy Sharp coined the term in a 2009 book and blog post. If the feature exists in the browser, the polyfill lets the browser do its thing, if not, the polyfill steps in to plug the missing functionality. They fill in the holes of older browsers, the missing features we want to use today. It replicates a native API with non-native code.
What Missing Features Are We Talking About?
In 2009, the 5th Edition of ECMAScript landed. It was a large and radical step forward for the language. ECMAScript 2015 delivered a similarly seismic update. Going forward, improvements to the language will be incremental, happening on a yearly basis. It’s an exciting time, with new features continually making their way into the language. Besides the core language itself, there’s also the DOM and the various APIs of the web platform.
To highlight the discrepancy between a modern and a legacy browser, here’s a comparison of the latest Chrome release versus Internet Explorer 9 (which some companies still sadly mandate support for). And here’s a table showing support for ECMAScript 6. The second table only goes as far back as IE 11, which as you can see supports practically zero ES6 features. That’s a lot of missing features…
Polyfills vs Transpiling
So clearly, from looking at the above tables, we need to transpile our code. It takes your shiny new syntax and spits out plain old-fashioned ECMAScript 5. If you want to utilize arrow functions, async/await, rest and spread parameters, classes, et al in your code, you need to transpile your ES6 code into ES5 with a tool such as Babel.
However, you can’t polyfill the syntax of JavaScript. While Babel will take your arrow functions and turn them into regular functions, a polyfill will add methods to the global scope and to native prototypes. Babel offers its own ES6 polyfill that, in the words of the Babel website, offers “new built-ins like Promise or WeakMap, static methods like Array.from or Object.assign, instance methods like Array.prototype.includes, and generator functions."
So the Babel polyfill can give us all the ES6 features we want. But there’s plenty it leaves out. Maybe you add and remove classes with the classList API or conduct media queries with matchMedia, but you still need to support IE9. Luckily there’s a service that provides everything the Babel polyfill covers, and a whole lot more.
Continue reading %A Beginner’s Guide to HTML5 Cross-Browser Polyfills%

Link: https://www.sitepoint.com/html5-cross-browser-polyfills/

How to Bundle a Simple Static Site Using Webpack

Webpack is all the rage right now. It has over 30,000 stars on GitHub and has been embraced by some of the big guns in the JavaScript world, such as the React and Angular.
However, you don’t need to be working on a large-scale project to take advantage of Webpack. Webpack is primarily a bundler, and as such you can also use it to bundle just about any resource or asset you care to think of.
In this article, I’m going to show you how to install and configure Webpack, then use it to create a minified bundle for a simple static site with a handful of assets.
But Why Would You Want to Do That?
Good question. Glad you asked!
One of the primary reasons for doing this is to minimize the number of HTTP requests you make to the server. As the average web page grows, you’ll likely include jQuery, a couple of fonts, a few plugins, as well as various style sheets and some JavaScript of your own. If you’re making a network request for each of these assets, things soon add up and your page can become sluggish. If you include all of the above in one bundle however, that problem disappears.
Webpack also makes it easy to minify your code, further reducing its size, and it lets you write your assets in whatever flavor you desire. For example, in this article I will demonstrate how to have Webpack transpile ES6 to ES5. This means you can write JavaScript using the latest, most up-to-date syntax (although this might not be fully supported yet), then serve the browsers ES5 that will run almost everywhere.
And finally, it’s a fun learning exercise. Whether or not you employ any of these techniques in your own projects is up to you, but by following along you’ll get a firm understanding of what Webpack does, how it does it and whether it’s a good fit for you.
Getting up and Running
The first thing you’ll need is to have Node and npm installed on your computer. If you haven’t got Node yet, you can either download it from the Node website, or you can download and install it with the aid of a version manager. Personally, I much prefer this second method, as it allows you to switch between multiple versions of Node and it negates a bunch of permissions errors, which might otherwise see you installing Node packages with admin rights.
We’ll also need a skeleton project to work with. Here’s one I made earlier. To get it running on your machine, you should clone the project from GitHub and install the dependencies.
git clone https://github.com/sitepoint-editors/webpack-static-site-example
cd webpack-static-site-example
npm i

This will install Slick Slider and Lightbox2 — two plugins we’ll be using on the site — to a node_modules folder in the root of the project.
After that you can open index.html in your browser and navigate the site. You should see something like this:

If you need any help getting with any of the steps above, why not head over to our forums and post a question.
Introducing Webpack to the Project
The next thing we’ll need to do is to install Webpack. We can do this with the following command:
npm i webpack –save-dev

This will install Webpack and add it as a devDependency to your package.json file:
“devDependencies": {
"webpack": "^3.2.0"
}

Next we’ll make a dist folder which will contain our bundled JavaScript.
mkdir dist

Now we can try and run Webpack from the command line to see if it is set up correctly.
./node_modules/webpack/bin/webpack.js ./src/js/main.js ./dist/bundle.js

What I am doing here is telling Webpack to bundle the contents of src/js/main.js into dist/bundle.js. If everything is installed correctly, you should see something like this output to the command line:
Hash: 1856e2c19ecd9b2d9026
Version: webpack 3.2.0
Time: 50ms
Asset Size Chunks Chunk Names
bundle.js 2.67 kB 0 [emitted] main
[0] ./src/js/main.js 192 bytes {0} [built]

And Webpack will create a bundle.js file in the dist folder. If you have a look at that file in your text editor of choice, you’ll see a bunch of boilerplate and the contents of main.js at the bottom.
Automating Our Setup
Now if we had to type all of the above into the terminal every time we wanted to run Webpack, that’d be quite annoying. So let’s create an npm script we can run instead.
In package.json, alter the scripts property to look like this:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack ./src/js/main.js ./dist/bundle.js"
},

Notice how we can leave out the full path to the Webpack module, as when run from a script, npm will automatically look for the module in the node_modules folder. Now when you run npm run build, the same thing should happen as before. Cool, eh?
Create a Webpack Configuration File
Notice how we’re passing the path of the file to bundle and the path of the output file as arguments to Webpack? Well, we should probably change that and specify these in a configuration file instead. This will make our life easier when we come to use loaders later on.
Create a webpack.config.js file in the project root.
touch webpack.config.js

And add the following code.
module.exports = {
entry: ‘./src/js/main.js’,
output: {
path: __dirname + ‘/dist’,
filename: ‘bundle.js’
}
}

And change the npm script to the following:
"scripts": {

"build": "webpack"
},

In webpack.config.js we are specifying the entry point and output location of the bundle as properties of the configuration object, which we are then exporting . Run everything again and it should all work as before.
Continue reading %How to Bundle a Simple Static Site Using Webpack%

Link: https://www.sitepoint.com/bundle-static-site-webpack/

6 jQuery-inspired Native DOM Manipulation Methods You Should Know

When jQuery was released, one of the main reasons behind its meteoric rise to popularity was the ease with which it could select DOM elements, traverse them and modify their content. But that was way back in 2006. In those days we were stuck with Internet Explorer 7 and ECMAScript 5 was still a couple of years off.

Luckily, a lot has changed since then. Browsers have become considerably more standards compliant and native JavaScript has improved in leaps and bounds. And as things have improved, we have seen people questioning whether we still need jQuery. I’m not going to get into that argument here, rather I’d like to offer some food for thought, as I present six native DOM manipulation methods which were inspired by this great library. These are as follows:

append()
prepend()
after()
before()
replaceWith()
remove()

In this article I want to examine the similarities and the differences between these native DOM manipulation methods and their jQuery counterparts. Then hopefully, the next time you find yourself including jQuery for the sake of a convenience method or two, you might opt to embrace the power of vanilla JavaScript instead.
1. append()
The append method performs an insertion operation, that is, it adds nodes to the DOM tree. As the name indicates, it appends the passed arguments to the list of children of the node on which it is invoked. Consider the following example:
const parent = document.createElement(‘div’)
const child1 = document.createElement(‘h1’)
parent.append(child1)
parent.outerHTML
//

<h1></h1></div>

const child2 = document.createElement(‘h2’)
parent.append(child2)
parent.outerHTML
// <div><h1></h1><h2></h2></div>

At this point you would be forgiven for asking how this differs from the native appendChild method. Well, a first distinction is that append() can take multiple arguments at once, and the respective nodes will be appended to the list of children, just like the jQuery append method. Continuing the previous snippet:
const child3 = document.createElement(‘p’)
const child4 = document.createElement(‘p’)
const child5 = document.createElement(‘p’)
parent.append(child3, child4, child5)
parent.outerHTML
/* Outputs:
<div>
<h1></h1>
<h2></h2>
<p></p>
<p></p>
<p></p>
</div>
*/

Furthermore, an argument can be even a string. So, while with appendChild() a rather verbose syntax must be employed:
parent.appendChild(document.createTextNode(‘just some text’))

with append() the same operation is shorter:
parent.append(‘just some text’)
parent.outerHTML
/* Outputs:
<div>
<h1></h1>
<h2></h2>
<p></p>
<p></p>
<p></p>
just some text
</div>
*/

The string is converted to a Text node, so any HTML is not parsed:
parent.append(‘<p>foo</p>’)
parent.outerHTML
/* Outputs:
<div>
<h1></h1>
<h2></h2>
<p></p>
<p></p>
<p></p>
just some text
<p&gt;foo&lt;/p&gt;
</div>
*/

This is in contrast to the jQuery method, where strings of markup are parsed and the corresponding nodes are generated and inserted into the DOM tree.
As is usually the case, if the appended node it is already present in the tree, it is first removed from its old position:
const myParent = document.createElement(‘div’)
const child = document.createElement(‘h1’)
myParent.append(child)
const myOtherParent = document.createElement(‘div’)
const myOtherParent.append(child)
myOtherParent.outerHTML
// <div><h1></h1></div>

myParent.outerHTML
// <div></div>”

A final difference between append() and appendChild() is that the latter returns the appended node, whereas the former returns undefined.
2. prepend()
The prepend method is very similar to append(). Children are added, but this time they are prepended to the list of children of the node on which the method is called, just before the first child:
const parent = document.createElement(‘div’)
const child1 = document.createElement(‘p’)
parent.prepend(child1)
parent.outerHTML
// <div><p></p></div>

const child2 = document.createElement(‘h2’)
parent.prepend(‘just some text’, child2)
parent.outerHTML
/* Outputs:
<div>
just some text
<h2></h2>
<p></p>
</div>
*/

The return value of the method is undefined. The corresponding jQuery method is prepend().
3. after()
The after method is another insertion method, but this time it must be called on a child node, that is, a node with a definite parent. Nodes are inserted as adjacent siblings, as can be seen in the following example:
const parent = document.createElement(‘ul’)
const child = document.createElement(‘li’)
child.append(‘First item’)
parent.append(child)
child.after(document.createElement(‘li’))
parent.outerHTML
// <ul><li>First item</li><li></li></ul>

The return value is undefined and in jQuery the similar operation is after().
4. before()
The before method is similar to after(), but now the nodes are inserted before the child node:
const parent = document.createElement(‘ul’)
const child = document.createElement(‘li’)
child.append(‘First item’)
parent.append(child)

const child1 = document.createElement(‘li’)
child1.append(‘Second item’)

const child2 = document.createElement(‘li’)
child2.append(‘Third item’)

child.before(child1, child2)

parent.outerHTML
/* Outputs:
<ul>
<li>Second item</li>
<li>Third item</li>
<li>First item</li>
</ul>
*/

Once again, the return value is undefined. The respective jQuery method is before().
Continue reading %6 jQuery-inspired Native DOM Manipulation Methods You Should Know%

Link: https://www.sitepoint.com/native-dom-manipulation-methods/

A Practical Guide to Planning a MEAN Stack Application

A Practical Guide to Planning a MEAN Stack Application is an excerpt from Manning’s Getting MEAN with Mongo, Express, Angular, and Node, Second Edition. Getting MEAN, Second Edition is completely revised and updated to cover Angular 2, Node 6 and the latest mainstream release of JavaScript ES2015 (ES6). This Second Edition will walk you through how to develop web applications using this updated MEAN stack.
Planning a Real Application
For the purposes of this article, let’s imagine that we’re building a working application on the MEAN stack called Loc8r. Loc8r will list nearby places with WiFi where people can go and get some work done. It will also display facilities, opening times, a rating, and a location map for each place.
Planning the MEAN Stack Application at a High Level
The first step is to think about what screens we’ll need in our application. We’ll focus on the separate page views and the user journeys. We can do this at a high level, not concerning ourselves with the details of what’s on each page. It’s a good idea to sketch out this stage on a piece of paper or a whiteboard, as it helps to visualize the application in its entirety. It also helps with organizing the screens into collections and flows, serving as a good reference point when we build it. As there’s no data attached to the pages or application logic behind them, it’s easy to add and remove parts, change what’s displayed and where, and even change how many pages we want. The chances are that we won’t get it right the first time; the key is to start and iterate and improve until we’re happy with the separate pages and overall user flow.
Planning the Screens
Let’s think about Loc8r. As stated our aim is as follows:

Loc8r will list nearby places with WiFi where people can go and get some work done. It displays facilities, opening times, a rating, and a location map for each place. Visitors can to submit ratings and reviews.

From this we can get an idea about some of the screens we’re going to need:

A screen that lists nearby places
A screen that shows details about an individual place
A screen for adding a review about a place

We’ll probably also want to tell visitors what Loc8r is for and why it exists, and we should add another screen to the list:

A screen for “about us” information

Dividing the Screens into Collections
Next, we want to take the list of screens and collate them where they logically belong together. For example, the first three in the list are all dealing with locations. The About page doesn’t belong anywhere and it can go in a miscellaneous Others collection. Sketching this out brings us something like figure 1.

Figure 1: Collate the separate screens for our application into logical collections.
Having a quick sketch like this is the first stage in planning, and we need to go through this stage before we can start thinking about architecture. This stage gives us a chance to look at the basic pages, and to also think about the flow. Figure 1, for example, shows a basic user journey in the Locations collection, going from the List page, to a Details page, and then onto the form to add a review.
Continue reading %A Practical Guide to Planning a MEAN Stack Application%

Link: https://www.sitepoint.com/planning-mean-stack-application/