Building a WebRTC Video Chat Application with SimpleWebRTC

With the advent of WebRTC and the increasing capacity of browsers to handle peer-to-peer communications in real time, it’s easier than ever to build real-time applications. In this tutorial, we’ll take a look at SimpleWebRTC and how it can make our lives easier when implementing WebRTC. Throughout the article, we’ll be building a WebRTC video chat app with messaging features.

If you need a bit of a background regarding WebRTC and peer-to-peer communication, I recommend reading The Dawn of WebRTC and Introduction to the getUserMedia API.

What is SimpleWebRTC

Before we move on, it’s important that we understand the main tool that we’ll be using. SimpleWebRTC is a JavaScript library that simplifies WebRTC peer-to-peer data, video, and audio calls.

SimpleWebRTC acts as a wrapper around the browser’s WebRTC implementation. As you might already know, browser vendors don’t exactly agree on a single way of implementing different features, which means that for every browser there’s a different implementation for WebRTC. As the developer, you’d have to write different code for every browser you plan to support. SimpleWebRT acts as the wrapper for that code. The API that it exposes is easy to use and understand, which makes it a really great candidate for implementing cross-browser WebRTC.

Building the WebRTC Video Chat App

Now it’s time to get our hands dirty by building the app. We’ll build a single page application that runs on top of an Express server.

Please note that you can download the code for this tutorial from our GitHub repo. To run it, or to follow along at home, you’ll need to have Node and npm installed. If you’re not familiar with these, or would like some help getting them installed, check out our previous tutorials:

You also need a PC or laptop that has a webcam. If not, you’ll need to get yourself a USB webcam that you can attach to the top of your monitor. You’ll probably need a friend or a second device to test remote connections.

Dependencies

We’ll be using the following dependencies to build our project:

  • SimpleWebRTC — the WebRTC library
  • Semantic UI CSS — an elegant CSS framework
  • jQuery — used for selecting elements on the page and event handling.
  • Handlebars — a JavaScript templating library, which we’ll use to generate HTML for the messages
  • Express — NodeJS server.

Project Setup

Go to your workspace and create a folder simplewebrtc-messenger. Open the folder in VSCode or your favorite editor and create the following files and folder structure:

simplewebrtc-messenger
├── public
│   ├── images
│   │   └── image.png
│   ├── index.html
│   └── js
│       └── app.js
├── README.md
└── server.js

Or, if you prefer, do the same via the command line:

mkdir -p simplewebrtc-messenger/public/{images,js}
cd simplewebrtc-messenger
touch public/js/app.js public/index.html .gitignore README.md server.js

Open README.md and copy the following content:

# Simple WebRTC Messenger

A tutorial on building a WebRTC video chat app using SimpleWebRTC.

Add the line node_modules to the .gitignore file if you plan to use a git repository. Generate the package.json file using the following command:

npm init -y

You should get the following output:

{
  "name": "simplewebrtc-messenger",
  "version": "1.0.0",
  "description": "A tutorial on building a WebRTC video chat app using SimpleWebRTC.",
  "main": "server.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Now let’s install our dependencies:

npm install express handlebars jquery semantic-ui-css simplewebrtc

As the installation proceeds, copy this code to server.js:

const express = require('express');

const app = express();
const port = 3000;

// Set public folder as root
app.use(express.static('public'));

// Provide access to node_modules folder from the client-side
app.use('/scripts', express.static(`${__dirname}/node_modules/`));

// Redirect all traffic to index.html
app.use((req, res) => res.sendFile(`${__dirname}/public/index.html`));

app.listen(port, () => {
  console.info('listening on %d', port);
});

The server code is pretty standard. Just read the comments to understand what’s going on.

Next, let’s set up our public/index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="scripts/semantic-ui-css/semantic.min.css">
  <title>SimpleWebRTC Demo</title>
  <style>
    html { margin-top: 20px; }
    #chat-content { height: 180px;  overflow-y: scroll; }
  </style>
</head>
<body>
  <!-- Main Content -->
  <div class="ui container">
    <h1 class="ui header">Simple WebRTC Messenger</h1>
    <hr>
  </div>

  <!-- Scripts -->
  <script src="scripts/jquery/dist/jquery.min.js"></script>
  <script src="scripts/semantic-ui-css/semantic.min.js"></script>
  <script src="scripts/handlebars/dist/handlebars.min.js "></script>
  <script src="scripts/simplewebrtc/out/simplewebrtc-with-adapter.bundle.js"></script>
  <script src="js/app.js"></script>
</body>
</html>

Next, let’s set up our base client-side JavaScript code. Copy this code to public/js/app.js:

window.addEventListener('load', () => {
  // Put all client-side code here
});

Finally, download this image from our GitHub repository and save it inside the public/images folder.

Now we can run our app:

npm start

Open the URL localhost:3000 in your browser and you should see the following:

Project setup

Continue reading %Building a WebRTC Video Chat Application with SimpleWebRTC%


Source: Sitepoint

Embarking On New Adventures: Inspiring Desktop Wallpapers For May 2018

Embarking On New Adventures: Inspiring Desktop Wallpapers For May 2018

Embarking On New Adventures: Inspiring Desktop Wallpapers For May 2018

Cosima Mielke

2018-04-30T13:15:44+02:00
2018-04-30T14:13:03+00:00

Sometimes it doesn’t take a lot to get inspired. A short ride with your bike, a coffee break with a friend, or listening to your favorite song might be just what you need to spark some fresh ideas. And if that doesn’t do it, we have a little extra inspiration boost for you: desktop wallpapers.

Since more than nine years, artists and designers from across the globe challenge their creative skills and design monthly wallpapers for you to indulge in. And, of course, it wasn’t any different this time around.

This post features their artworks for May 2018. The wallpapers all come in versions with and without a calendar, so that you can continue using your favorites even after the month has ended. Speaking of favorites: As a special goodie, we also added a selection of May wallpapers from previous years that are too good to be forgotten. A big thank-you to everyone who participated. Now there’s only one question left open: Which one to choose?

Please note that:

  • All images can be clicked on and lead to the preview of the wallpaper,
  • You can feature your work in our magazine by taking part in our Desktop Wallpaper Calendar series. We are regularly looking for creative designers and artists to be featured on Smashing Magazine. Are you one of them?

Leaves Of Grass

“For many, the month of May is the preferred month of the year. The nature blossoms, the birds sing, and leaves of grass sprout all around us. Coincidentally, this is the month at the end of which the poet Walt Whitman was born. As he said in his famous poetry collection: ‘Spontaneous me, Nature, The loving day, the mounting sun, the friend I am happy with, The arm of my friend hanging idly over my shoulder.’ Sounds like a perfect setting to fly a kite — so, let’s get to it!” — Designed by PopArt Studio from Novi Sad, Serbia.

Leaves Of Grass

Lake Deck

“I wanted to make a big painterly vista with some mountains and a deck and such.” — Designed by Mike Healy from Australia.

Lake Deck

It’s Finally May, My Deer

“After going through a super long winter, I was inspired to create this whimsical wallpaper because I wanted to highlight the beauty of nature and how I envision it to be during the warmer seasons that have yet to come.” — Designed by Michaela Schmidt from Maryland.

It’s Finally May, My Deer

Geo

Designed by Amanda Focht from the United States.

Geo

A River And A Dream

“A river with lush trees. Is it a dream? A beautiful sight in the middle of the Belgrade city. I can hear the music in the distance. Some retro sound. Earth, river, fresh air, the wind, blue sky, the music… I closed my eyes and the feeling of nostalgia for another time and adventurous spirit to travel around the world in a boat struck me suddenly. I opened my eyes slowly. Yes, the fisherman has finally caught the fish. You can’t ever feel unhappy strolling by the river and taking shots. Dream and be patient just like the fisherman, and maybe you will travel around the world in a boat.” — Designed by Marija Zaric from Belgrade, Serbia.

A River And A Dream

Magical Sunset

“I designed Magical Sunset as a friendly reminder to take a moment and enjoy life around you. Each sunset and sunrise brings a new day for greatness and a little magic.” — Designed by Carolyn Warcup from the United States.

Magical Sunset

What’s The Buzz?

“May is the start of the summer adventure. Whether its traveling, outdoors, or sunshine, it is a time that brings smiles. I used three objects to portray this idea. The passport is a key to traveling, the sound of bees and sight of them pollinating shows the outdoors, and the glasses represent the summer sunshine that is about to come.” — Designed by Maci Roos from Pottsville, PA.

What’s The Buzz?

May The Fourth Be With Y’All!

“In honor of Star Wars day, I created this Millennium Falcon island. Wouldn’t it be fun to set sail to a beach vacation paradise… a long time ago in a galaxy far far away?” — Designed by Phil Scroggs from the United States.

May The Fourth Be With Y’All!

Growth At The Cost Of Green

“Imagine going deep into the woods, feeling the plush green breath of nature. A space devoid of chaos and pollution. A luxury one could rarely afford in the current world. The land that remains today is unnatural, with huge tractors sprawling into, greedily craving for soil and more ‘convenience’ for humans. Deforestation surely represents one of the major concerns in global land use.” — Designed by Sweans from London.

Growth At The Cost Of Green

Skiing!

Designed by Mohan Shen from China.

Skiing!

World No-Tobacco Day 2018

“Smoking does not make you a killer per se, but your heart will drown in guilt if second-hand smoke gave someone in your own family a life-threatening disease. Save a lifetime of regret — quit today.” — Designed by Dipanjan Karmakar from India.

World No-Tobacco Day 2018

Oldies But Goodies

Some things are too good to gather dust. That’s why we dug deep into our wallpaper archieves to rediscover some May favorites from past years. Please note that they hence don’t come with a calendar. Enjoy!

Welcome May With An Ice Cream!

“May is the last month of spring, the weather is getting hotter every day and it starts to feel almost like summer… So, the best thing to cool ourselves and bring summer closer is to… welcome May with an ice cream!” — Designed by WebOlution from Greece.

Welcome May With An Ice Cream!

Be On Your Bike!

“May is National Bike Month! So, instead of hopping in your car, grab your bike and go. Our whole family loves that we live in our bike-friendly community. So, bike to work, to school, to the store, or to the park — sometimes it is faster. Not only is it good for the environment, but it is great exercise!” — Designed by Karen Frolo from the United States.

Be On Your Bike!

Understand Yourself

“Sunsets in May are the best way to understand who you are and where you are heading. Let’s think more!” — Designed by Igor Izhik from Canada.

Understand Yourself

Poppies Paradise

Designed by Nathalie Ouederni from France.

Poppies Paradise

Field Wild Flowers

“Springtime festival celebrated with May blossoms.” — Designed by Richard George Davis from South Africa.

Field Wild Flowers

May The Force Be With You

“Yoda is my favorite Star Wars character and “may” has funny double meaning.” — Designed by Antun Hirsman from Croatia.

May The Force Be With You

Beautiful Things

Designed by Elise Vanoorbeek from Belgium.

Beautiful Things

World’s Labor Day

Designed by Debobrata Debnath from India.

World's Labor Day

The Master Of Disguise

Designed by Sasha Endoh from Canada.

Octopus: The Master of Disguise

The Green Bear

Designed by Pedro Rolo from Portugal.

The Green Bear

Tentacles

Designed by Julie Lapointe from Canada.

Smashing Wallpaper - may 12

Japan

“Japan is the land of the rising sun.” — Designed by Cheloveche.ru from Russia.

Smashing Wallpaper - may 12

La Ensalada

Designed by Xenia Latii from the United States.

Smashing Wallpaper - May 2011

Rainy Days

“Winter is nearly here in my part of the world and I think rainy days should be spent at home with a good book!” — Designed by Tazi Design from Australia.

Rainy Days

Who Is Your Mother?

“Someone who wakes up early in the morning, cooks you healthy and tasty meals, does your dishes, washes your clothes, sends you off to school, sits by your side and cuddles you when you are down with fever and cold, and hugs you when you have lost all hopes to cheer you up. Have you ever asked your mother to promise you never to leave you? No. We never did that because we are never insecure and our relationship with our mothers is never uncertain. We have sketched out this beautiful design to cherish the awesomeness of motherhood. Wishing all a happy Mothers Day!” — Designed by Acodez IT Solutions from India.

Who Is Your Mother?

Add Color To Your Life!

“This month is dedicated to flowers, to join us and brighten our days giving a little more color to our daily life.” — Designed by Verónica Valenzuela from Spain.

Add Color To Your Life!

Let’s Have Some Fun In The Sun

“May takes us down a lane of memories along with the stories of summer that cling to us, so we designed a wallpaper to remind everyone of the warmth of happiness while the sun shines. Summer is the time of the year when we are in a holiday mood and also we make it a point to take some time to chill out with people dear to us.” — Designed by Acodez from India.

Let’s Have Some Fun In The Sun

MonkGolfier

“We recently changed our workplace and now we’re in a windy place, so we like the idea of flying in the air, somehow.” — Designed by Monk Software from Italy.

MonkGolfier

Colorful

Designed by Lotum from Germany.

Smashing Wallpaper - may 12

Join In Next Month!

Please note that we respect and carefully consider the ideas and motivation behind each and every artist’s work. This is why we give all artists the full freedom to explore their creativity and express emotions and experience throughout their works. This is also why the themes of the wallpapers weren’t anyhow influenced by us, but rather designed from scratch by the artists themselves.

Thank you to all designers for their participation. Join in next month!


Source: Smashing Magazine

10 Essential Sublime Text Plugins for JavaScript Developers

In this article, I’ll outline ten must-have Sublime Text plugins for JavaScript developers, each of which can improve your workflow and make you more productive.

Sublime Text is a great application for just about any developer to have in their toolbox. It’s a cross-platform, highly customizable, advanced text editor that sits nicely between full featured IDEs (which are notoriously resource hungry) and command line editors such Vim or Emacs (which have steep learning curves).

In recent years, Sublime has gained welcome competition from both Visual Studio Code and Atom, but Sublime Text still holds its own by being indisputably faster, being able to open larger files faster than the others.

One of the things that makes Sublime so great is its extensible plugin architecture. This makes it easy for developers to extend Sublime’s core functionality with new features like code completion, or the embedding of remote API documentation. Sublime Text doesn’t come with plugins enabled out of the box: they’re typically installed through a 3rd-party package manager simply called Package Control. To install Package Control in Sublime Text, please follow the installation guide on their website.

So let’s get to it!

1. Babel

Of course, the first one on my list is the Babel plugin. This plugin adds proper syntax highlighting to your ES6/2015 and React JSX code. After installing the plugin, the first thing you should do is set it as the default syntax for all of your JavaScript and TypeScript file types.

If you haven’t yet discovered the joy of Babel, I highly suggest it. It allows you to compile ES6/ES7/ESNext, JSX, and TypeScript code down to ES5 for full browser support. It integrates well with all popular build tools and the CLI. Obviously, it doesn’t support legacy browsers, but you can follow the tips on their caveats page if you need to support IE10 and below.

Babel

2. SublimeLinter

Next up is SublimeLinter, which provides amazing ESLint and JSHint integration into Sublime. A linter will look over your code and verify it has proper styling and proper syntax based on a configuration file that can be checked in with your source code. No matter if you’re a beginner or have been programming for most of your life: in JavaScript, a linter is a must have. Check out the ESLint or JSHint about pages to see what they can do for you. Depending on which you chose for your project, you’ll also need the supporting packages of SublimeLinter-eslint or SublimeLInter-jshint.

In order for either of these to work, you must include a linter either into your project dependencies or install it globally:

npm install --save-dev eslint

If you’re unsure how to use npm, check out our tutorial on getting started with Node Package Manager.

Screenshot of the SublimeLinter plugin highlighting some problem code and displaying the error in the status bar

If you’ve installed and configured it correctly, you should see the changes when you open or save a JavaScript file. The plugin is incredibly configurable and can be made to report in a number of ways that might be better for your workflow. By default, the description of the errors will be reported in the status bar at the bottom of the editor.

Continue reading %10 Essential Sublime Text Plugins for JavaScript Developers%


Source: Sitepoint

WordPress Local Development For Beginners: From Setup To Deployment

WordPress Local Development For Beginners: From Setup To Deployment

WordPress Local Development For Beginners: From Setup To Deployment

Nick Schäferhoff

2018-04-27T14:00:29+02:00
2018-04-27T12:15:55+00:00

When first starting out with WordPress, it’s very common to make any changes directly on your live site. After all, where else would you do it? You only have that one site, so when something needs changing, you do it there.

However, this practice has several drawbacks. Most of all that it’s very public. So, when something goes seriously wrong, it’s quite noticeable for people on your site.

Preventing Common Mistakes

When creating free or premium WordPress themes, you’re bound to make mistakes. Find out how you can avoid them in order to save yourself time and focus on actually creating themes people will enjoy using. Read more →

It’s ok, don’t feel bad. Most WordPress beginners have done this at one point or another. However, in this article, we want to show you a better way: local WordPress development.

What that means is setting up a copy of your website on your local hard drive. Doing so is incredibly useful. So, below we will talk about the benefits of building a local WordPress development environment, how to set one up and how to move your local site to the web when it’s ready.

This is important, so stay tuned!

The Benefits Of Local WordPress Development

Before diving into the how, let’s have a look at the why. Using a local development version of WordPress offers many benefits.

We already mentioned that you no longer have to make changes to your live site with all the risks involved with that. However, there is more:

  • Test themes and plugins
    With a local copy of your site, you can try out as many themes and plugin combinations as you want without risking taking your live site out due to incompatibilities.
  • Update safely
    Another time when things are prone to go wrong are updates. With a local environment, you can update WordPress core and components to see if there are any problems before applying the updates to your live site.
  • Independent of an online connection
    With your WordPress site on your computer, you can work on it without being connected to the Internet. Thus, you can get work done even if there is no wifi.
  • High performance/low cost
    Because site performance is not limited by an online connection, local sites usually run much faster. This makes for a better workflow. Also, as you will see, you can set it all up with free software, eliminating the need for a paid staging area.

Sounds good? Then let’s see how to make it happen.

How To Set Up A Local Development Environment For WordPress

In this next part, we will show you how to set up your own local WordPress environment. First, we will go over what you need to do and then how to get it right.

Tools You’ll Need

In order to run, WordPress needs a server. That’s true for an online site as well as a local installation. So, we need to find a way to set one up on our computer.

That server also needs some software WordPress requires to work. Namely, that’s PHP (the platform’s main programming language) and MySQL for the database. Plus, it’s nice to have a MySQL user interface like phpMyAdmin to make handling the database more convenient.

In addition to that, need your favorite code editor or IDE (integrated development environment) for the coding part. My choice is Notepad++ but you might have your own preferences.

Finally, it’s useful to have some developer tools to analyze and debug your site, for example, to look at HTML and CSS. The easiest way is to use Chrome or Firefox (read our article on Firefox’s DevTools), which have extensive functionality like that built in.

Available Software

We have several options at our disposal to set up local server environments. Some of the most well known are DesktopServer, Vagrant, and Local by Flywheel. All of these contain the necessary components to set up a local server that WordPress can run on.

For this tutorial we will use XAMPP. The name is an acronym and stands for “cross platform, Apache, MySQL, PHP, Perl”. If you have been paying attention, you will notice that we earlier noted MySQL and PHP as essential to running a WordPress website. In addition, Apache is an open source solution for creating servers. So, the software contains everything we need in one neat package. Plus, as “cross platform” suggests, XAMPP is available for both Windows, Mac and Linux computers.

To continue, if you haven’t done so already, head over to the official XAMPP website and download a copy.

How To Use XAMPP

Installing XAMPP pretty much works like every other piece of software.

On Windows:

  1. Run the installer (note that you might get a warning about running unknown software, allow to continue).
  2. When asked which components to install, make sure that Apache, MySQL, PHP, and phpMyAdmin are active. The rest is usually unnecessary, deactivate it unless you have good reason not to.
  3. Choose the location to install. Make sure it’s easy to reach as that’s where your sites will be saved and you will probably access them often.
  4. You can disregard the information about Bitnami.
  5. Choose to start the control panel right away at the end.

On Mac:

  1. Open the .dmg file
  2. Double click on the XAMPP icon or drag it to applications folder
  3. That’s it, well done!

After the installation is complete, the control panel starts. Should your operating system ask for Firewall permissions, make sure to allow XAMPP for private networks, otherwise, it won’t work.

Large preview

From the panel, you can start Apache and MySQL by clicking the Start buttons on the respective rows. If you run into problems with programs that use the same ports as XAMPP, quit those programs and try to restart the XAMPP processes. If the problem is with Skype, there is a permanent solution by disabling the ports under Tools → Options → Advanced → Connections.

Large preview

Under Config, you can also enable automatic start for the components you need.

Large preview

After that, it’s time to test your local server. For that, open your browser, and go to http://localhost.

If you see the following screen, everything works as it should. Well done!

Large preview

Installing WordPress Locally

Now that you have a local server, you can install WordPress in the same way that you do on a web server. The only difference: everything is done on your hard drive, not an FTP server or inside a hosting provider’s admin panel.

That means, to create a database for WordPress, you can simply go to http://localhost/phpmyadmin. Here, you find the same options as in the online version and can create a database, user and password for WordPress.

Large preview

Once that is done and you want to install WordPress, you can do so via the htdocs folder inside your installation of XAMPP. There, simply create a new directory, download the latest version of WordPress, unpack the files and copy them into the new folder. After that, you can start the installation by going to http://localhost/newdirectoryname.

Large preview

That’s basically it. Now that you have a running copy of WordPress on your website, you can install themes and plugins, set up a child theme, change styles, create custom page templates and do whatever your heart desires.

When you are satisfied, you can then move the website from a local installation to live environment. That’s what we will talk about next.

How To Deploy Your Site With A Plugin

Alright, once your local site is up to your liking, it’s time to get it online. Just a quick note: if you want to get a copy of your existing live site to your hard drive, you can use the same process as described below only in reverse. The overall principles stay the same.


Source: Smashing Magazine

Join Us at Awwwards San Francisco 2018

This article was created in partnership with Awwwards. Thank you for supporting the partners who make SitePoint possible.

From Thursday, May 10 to Friday, May 11, Awwwards will be hosting its San Francisco 2018 conference at the Palace of Fine Arts.

Awwwards San Francisco 2018

Awwwards San Francisco 2018 is an event for designers, web developers and digital dreamers.

Stay on the cutting edge of your field with 20+ talks on such topics as design, UI animation, chatbots, VR, experimental thinking, iterative design and self-driving cars.

The speakers have a lot to offer and include Treehouse’s Ryan Carson, Uber’s Molly Nix, Dann Petty, Chris Cloud, Amazon design lead Jina Anne, Behance co-founder Matias Corea and many more.

Come to Awwwards San Francisco for the:

  • Networking – immerse yourself with the leaders of the tech and design world.
  • Experience – Meet people who you follow online, all food and drinks included.
  • Knowledge – Don’t wait until you read about it online.

Afterwards, join your fellow conference goers for a waterfront party at The General’s Residence, Fort Mason with an open bar and canapès.

Find out more and get your tickets over at Awwwards!

Continue reading %Join Us at Awwwards San Francisco 2018%


Source: Sitepoint

Want to Build Stunning Sites? Use These Multipurpose WP Themes

This article was created in partnership with BAWMedia. Thank you for supporting the partners who make SitePoint possible. Multipurpose WordPress themes like those listed here are great for any web designer. They are more than suitable for just about anything in terms of website types or uses that you can throw at them. The old […]

Continue reading %Want to Build Stunning Sites? Use These Multipurpose WP Themes%


Source: Sitepoint

Setting up an ES6 Project Using Babel and webpack

In this article, we’re going to look at creating a build setup for handling modern JavaScript (running in web browsers) using Babel and Webpack.

This is needed to ensure that our modern JavaScript code in particular is made compatible with a wider range of browsers than it might otherwise be.

JavaScript, like most web-related technologies, is evolving all the time. In the good old days, we could drop a couple of <script> tags into a page, maybe include jQuery and a couple of plugins, then be good to go.

However, since the introduction of ES6, things have got progressively more complicated. Browser support for newer language features is often patchy, and as JavaScript apps become more ambitious, developers are starting to use modules to organize their code. In turn, this means that if you’re writing modern JavaScript today, you’ll need to introduce a build step into your process.

As you can see from the links beneath, converting down from ES6 to ES5 dramatically increases the number of browsers that we can support.

The purpose of a build system is to automate the workflow needed to get our code ready for browsers and production. This may include steps such as transpiling code to a differing standard, compiling Sass to CSS, bundling files, minifying and compressing code, and many others. To ensure these are consistently repeatable, a build system is needed to initiate the steps in a known sequence from a single command.

Prerequisites

In order to follow along, you’ll need to have both Node.js and npm installed (they come packaged together). I would recommend using a version manager such as nvm to manage your Node installation (here’s how), and if you’d like some help getting to grips with npm, then check out SitePoint’s beginner-friendly npm tutorial.

Set Up

Create a root folder somewhere on your computer and navigate into it from your terminal/command line. This will be your <ROOT> folder.

Create a package.json file with this:

npm init -y

Note: The -y flag creates the file with default settings, and means you don’t need to complete any of the usual details from the command line. They can be changed in your code editor later if you wish.

Within your <ROOT> folder, make the directories src, src/js, and public. The src/js folder will be where we’ll put our unprocessed source code, and the public folder will be where the transpiled code will end up.

Transpiling with Babel

To get ourselves going, we’re going to install babel-cli, which provides the ability to transpile ES6 into ES5, and babel-preset-env, which allows us to target specific browser versions with the transpiled code.

npm install babel-cli babel-preset-env --save-dev

You should now see the following in your package.json:

"devDependencies": {
  "babel-cli": "^6.26.0",
  "babel-preset-env": "^1.6.1"
}

Whilst we’re in the package.json file, let’s change the scripts section to read like this:

"scripts": {
  "build": "babel src -d public"
},

This gives us the ability to call Babel via a script, rather than directly from the terminal every time. If you’d like to find out more about npm scripts and what they can do, check out this SitePoint tutorial.

Lastly, before we can test out whether Babel is doing its thing, we need to create a .babelrc configuration file. This is what our babel-preset-env package will refer to for its transpile parameters.

Create a new file in your <ROOT> directory called .babelrc and paste the following into it:

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "browsers": ["last 2 versions", "safari >= 7"]
        }
      }
    ]
  ]
}

This will set up Babel to transpile for the last two versions of each browser, plus Safari at v7 or higher. Other options are available depending on which browsers you need to support.

With that saved, we can now test things out with a sample JavaScript file that uses ES6. For the purposes of this article, I’ve modified a copy of leftpad to use ES6 syntax in a number of places: template literals, arrow functions, const and let.

"use strict";

function leftPad(str, len, ch) {
  const cache = [
    "",
    " ",
    "  ",
    "   ",
    "    ",
    "     ",
    "      ",
    "       ",
    "        ",
    "         "
  ];
  str = str + "";
  len = len - str.length;
  if (len <= 0) return str;
  if (!ch && ch !== 0) ch = " ";
  ch = ch + "";
  if (ch === " " && len < 10)
    return () => {
      cache[len] + str;
    };
  let pad = "";
  while (true) {
    if (len & 1) pad += ch;
    len >>= 1;
    if (len) ch += ch;
    else break;
  }
  return `${pad}${str}`;
}

Save this as src/js/leftpad.js and from your terminal run the following:

npm run build

If all is as intended, in your public folder you should now find a new file called js/leftpad.js. If you open that up, you’ll find it no longer contains any ES6 syntax and looks like this:

"use strict";

function leftPad(str, len, ch) {
  var cache = ["", " ", "  ", "   ", "    ", "     ", "      ", "       ", "        ", "         "];
  str = str + "";
  len = len - str.length;
  if (len <= 0) return str;
  if (!ch && ch !== 0) ch = " ";
  ch = ch + "";
  if (ch === " " && len < 10) return function () {
    cache[len] + str;
  };
  var pad = "";
  while (true) {
    if (len & 1) pad += ch;
    len >>= 1;
    if (len) ch += ch;else break;
  }
  return "" + pad + str;
}

Continue reading %Setting up an ES6 Project Using Babel and webpack%


Source: Sitepoint

How to Find and Fix Poor Page Load Times With Raygun

In this tutorial, we’ll focus on finding and fixing poor page load times with Raygun. But before we do that, let’s discuss why slightly longer page load times can be such a big deal.

One of the most important things that you can do to make a good first impression on potential customers or clients visiting your website is improve its loading speed.

Imagine a customer who just heard about your company from a friend. You sell a product online which users can purchase by visiting your website. If different website pages are taking a long time to load and you are not selling that product exclusively, there is a good chance that the customer will abandon your site and go somewhere else.

You did not just miss out on your first sale here, you also missed the opportunity to have a loyal customer who would have purchased more products in the future. 

That’s the thing with the Internet—people are just a few clicks away from leaving your website and buying something from your competitors. Faster loading pages can give you an edge over competitors and increase your revenue.

How Can Raygun Help?

Raygun relies on Real User Monitoring Insights (RUM Insights) to improve a website’s performance and page load time. The term “Real User Monitoring” is the key here. You could use tools like WebPagetest and Google Page Speed Insights to optimize individual pages, but those results will not be based on real user data. On the other hand, the data provided by Raygun is based on real users who visited your website.

Raygun also presents the information in a more organized manner by telling you things like the average page speed for the website, the most requested pages, and the slowest pages. This way, you can prioritize which page or section of the website needs to be optimized first.

You can also see how fast the website is loading for users in different countries or for users with different browsers. Similarly, you can compare the speed of your website on mobile vs. desktop. 

Another advantage of Raygun is that it will show you how the website is performing for different users. For example, the website may be loading slowly for one of your most valuable clients. In such cases, you would definitely like to know about it and do something to improve their experience before it is too late.

We will learn how to do all that with Raygun in the next few sections of this article.

Integrating Raygun Into Your Website

You need to sign up for an account before integrating Raygun into your website. This account will give you access to all Raygun features for free for 14 days.

Once you have registered successfully, you can click on the Create Application button to create a new application. You can fill out a name for your application on the next screen and then check some boxes to receive notifications about errors and real user monitoring insights.

Create Raygun Application

Now you just have to select your development platform or framework. In this case, we are using JavaScript.

Choose Raygun Language or Framework

Finally, you will get some code that you have to add on all the pages you want to monitor. Instead of placing the following code in your website, you could also download the production or development version of the library and include it yourself.

Once you have added the above code snippet before the closing </head> tag, you have to place the following snippet just before the closing <body> tag.

If you don’t add any more code, Raygun will now start collecting anonymous data. This means that you will be able to know how your website is performing for different users, but there will be no way to identify those users.

There is an easy fix for this problem. All you have to do is add the following code in your webpages and Raygun will take care of the rest.

You will have to include these three pieces of code in all the pages that you want to track. Once done, the data will start showing up in the dashboard for you to analyze.

Finding Pages With Poor Load Times

The Real User Monitoring section in the Raygun dashboard has a lot of tabs to present the data in different formats. We will briefly go over all these tabs to show you how the information presented in them can be used to find pages with poor load times.

Raygun Live Sessions - Visiting Countries

The Live tab will give you an overview of your site’s performance in real time. It has different metrics like Health Score to show you how the site is currently performing. You can read more about all these metrics in the documentation for the Live tab on the Raygun website.

It also has a world map to point out the countries of your currently
active users. You will also find a list of most recent requests to your
website by different users. Here is an image showing the most recent requests to our website.

Live Tab - Recent Requests

The performance tab has five useful metrics to give you a quick overview of the website page load times. For example, a median load time of 1.41 seconds means that 50% of your pages load before 1.41 seconds have passed. Similarly, a P90 Load Time of 6.78 seconds tells you that 90% of the time, the website loads before 6.48 seconds.

Performance Tab

This should give you a rough idea of the performance of a website and how slow it is for the slowest 10% of users.

The performance tab also has a list of the slowest and most requested pages at the bottom. Knowing the most popular and the slowest pages can be very helpful when you want to prioritize which sections of your website need to be fixed first.

Even though all pages in a website should load as quickly as possible, some of these pages are more important than others. Therefore, you might be interested in finding out the performance of a particular page on a website. You can do so by simply typing the page you are looking for in the input field. This will give you information about the median, average, and P90 load time of a particular page. Here is the data for the home page of our website.

Page load time data for a sample website

You can use the Sessions tab to see session-related information like the total number of sessions, total number of users, and median session length. The sessions table will give you a quick overview of the last 150 sessions with information like the country, duration, total page views, and the last visited page for a session.

Clicking on the magnifying glass will show you more details of a particular session like the pages the user visited, the load time of those pages, and the browser/device used during the session.

The Users tab will give you an overview of the satisfaction level of different users with your website. This can be very helpful when you want to see how a particular user is interacting with your website and if or why their page load time is more than expected.

There are three other tabs to show information about all the page views in terms of browsers, platforms, and geography. This way you will be able to know if a webpage is loading slowly only on a particular browser or platform. You will also have a rough idea of the distribution of users. For instance, knowing if most of your clients are from a particular country or use a particular browser can be very handy.

Raygun lists the percentage of visitors from a particular continent at the top of the Geo tab. After that, it provides a map with the distribution of load times. Countries with the slowest load times are filled with red, and countries with quick load times are filled with green.

Raygun Geo Tab

If you are consistently getting poor loading times from a particular country, it might be worth your time to look closely and find out the reason.

Fixing Poor Page Load Times

In the previous section, we learned how to use all the data collected by Raygun to figure out which pages are taking a long time to load or if there are any countries where our page load times are longer than usual.

Now it is time to see how we can use Raygun to discover issues which might be causing a particular page or the whole website to load slower than usual.

Improving poor page load time of a website can be pretty overwhelming, especially if the website is very complicated or if it has a lot of pages. The trouble is in finding what to improve and where to start.

Luckily, Raygun can offer you some general insights to fix your website. You can click on the Insights options under the Real User Monitoring menu, and Raygun will scan your website for any potential issues. You can find a list of all these rules in the official Raygun documentation. Fixing all the listed issues will significantly speed up your website.

Raygun Insights Rules

Besides following these general guidelines, you might also want to isolate the pages that have been loading slowly. Once you have isolated them, Raygun can show you the time they take to resolve DNS, latency, SSL handshake, etc. This will give you a good idea of the areas where you can make improvements to reduce the page load time. The following image should make it clear.

About Us Page

You can also filter the data in order to get a more accurate picture of the load time for a particular page and various factors affecting it. The above image showed you the average latency for all requests made to the “About Us” page. However, you can click on the Add Filter button at the top and only see the “About Us” loading time graph for a specific country like Italy.

About Us Italy Filter

You will also see all the requests made by a specific page at the bottom. Basically, you will be able to see the DNS, latency, SSL, server, and transfer time for every resource loaded for a specific page and see if any of them is the culprit.

About Us Requests

Once you find out which resources are taking too long to load, you can start optimizing your pages.

Final Thoughts

As you saw in this tutorial, Raygun can be of great help to organizations looking to improve their page load times. It is super easy to integrate, and after successful integration, the data will simply start showing up in the dashboard without any intervention from your side.

Raygun also has different tabs to organize the collected data so that you can analyze it more easily and efficiently. For example, it can show you load times for different countries, browsers, and platforms. It also has filters that you can use to isolate a particular set of data from the rest and analyze it closely.

If you or your company are looking for an easy-to-integrate tool which can provide great insights about how your real users are interacting with your website, you should definitely give Raygun a try. You don’t have anything to lose since it is free for the first 14 days!

And while you’re here, check out some of our other tutorials on Raygun!


Source: Nettuts Web Development

Measuring Websites With Mobile-First Optimization Tools

Measuring Websites With Mobile-First Optimization Tools

Measuring Websites With Mobile-First Optimization Tools

Jon Raasch

2018-04-26T13:40:03+02:00
2018-04-26T14:11:08+00:00

Performance on mobile can be particularly challenging: underpowered devices, slow networks, and poor connections are some of those challenges. With more and more users migrating to mobile, the rewards for mobile optimization are great. Most workflows have already adopted mobile-first design and development strategies, and it’s time to apply a similar mindset to performance.

In this article, we’ll take a look at studies linking page speed to real-world metrics, and discuss the specific ways mobile performance impacts your site. Then we’ll explore benchmarking tools you can use to measure your website’s mobile performance. Finally, we’ll work with tools to help identify and remove the code debt that bloats and weighs down your site.

Responsive Configurators

How would you design a responsive car configurator? How would you deal with accessibility, navigation, real-time previews, interaction and performance? Let’s figure it out. Read article →

Why Performance Matters

The benefits of performance optimization are well-documented. In short, performance matters because users prefer faster websites. But it’s more than a qualitative assumption about user experience. There are a variety of studies that directly link reduced load times to increased conversion and revenue, such as the now decade-old Amazon study that showed each 100ms of latency led to a 1% drop in sales.

Page Speed, Bounce Rate & Conversion

In the data world, poor performance leads to an increased bounce rate. And in the mobile world that bounce rate may occur sooner than you think. A recent study shows that 53% of mobile users abandon a site that takes more than 3 seconds to load.

That means if your site loads in 3.5 seconds, over half of your potential users are leaving (and most likely visiting a competitor). That may be tough to swallow, but it is as much a problem as it is an opportunity. If you can get your site to load more quickly, you are potentially doubling your conversion. And if your conversion is even indirectly linked to profits, you’re doubling your revenue.

SEO And Social Media

Beyond reduced conversion, slow load times create secondary effects that diminish your inbound traffic. Search engines already use page speed in their ranking algorithms, bubbling faster sites to the top. Additionally, Google is specifically factoring mobile speed for mobile searches as of July 2018.

Social media outlets have begun factoring page speed in their algorithms as well. In August 2017, Facebook announced that it would roll out specific changes to the newsfeed algorithm for mobile devices. These changes include page speed as a factor, which means that slow websites will see a decline in Facebook impressions, and in turn a decline in visitors from that source.

Search engines and social media companies aren’t punishing slow websites on a whim, they’ve made a calculated decision to improve the experience for their users. If two websites have effectively the same content, wouldn’t you rather visit one that loads faster?

Many websites depend on search engines and social media for a large portion of their traffic. The slowest of these will have an exacerbated problem, with a reduced number of visitors coming to their site, and over half of those visitors subsequently abandoning.

If the prognosis sounds alarming, that’s because it is! But the good news is that there are a few concrete steps you can take to improve your page speeds. Even the slowest sites can get “sub three seconds” with a good strategy and some work.

Profiling And Benchmarking Tools

Before you begin optimizing, it’s a good idea to take a snapshot of your website’s performance. With profiling, you can determine how much progress you will need to make. Later, you can compare against this benchmark to quantify the speed improvements you make.

There are a number of tools that assess a website’s performance. But before you get started, it’s important to understand that no tool provides a perfect measurement of client-side performance. Devices, connection speeds, and web browsers all impact performance, and it is impossible to analyze all combinations. Additionally, any tool that runs on your personal device can only approximate the experience on a different device or connection.

In one sense, whichever tool you use can provide meaningful insights. As long as you use the same tool before and after, the comparison of each should provide a decent snapshot of performance changes. But certain tools are better than others.

In this section, we’ll walk through two tools that provide a profile of how well your website performs in a mobile environment.

Note: If can be difficult to benchmark an entire site, so I recommend that you choose one or two of your most important pages for benchmarking.

Lighthouse

One of the more useful tools for profiling mobile performance is Google’s Lighthouse. It’s a nice starting point for optimization since it not only analyzes page performance but also provides insights into specific performance issues. Additionally, Lighthouse provides high-level suggestions for speed improvements.


Lighthouse audit tab
Lighthouse in the Google’s Web Developer Tools. (Large preview)

Lighthouse is available in the Audits tab of the Chrome Developer Tools. To get started, open the page you want to optimize in Chrome Dev Tools and perform an audit. I typically perform all the audits, but for our purposes, you only need to check the ‘Performance’ checkbox:


Lighthouse audit selection
All the audits are useful, but we’ll only need the Performance audit. (Large preview)

Lighthouse focuses on mobile, so when you run the audit, Lighthouse will pop your page into the inspector’s responsive viewer and throttle the connection to simulate a mobile experience.

Lighthouse Reports

When the audit finishes, you’ll see an overall performance score, a timeline view of how the page rendered over time, as well as a variety of metrics:


Lighthouse performance audit results
In the performance audit, pay attention to the first meaningful paint. (Large preview)

It’s a lot of information, but one report to emphasize is the first meaningful paint, since that directly influences user bounce rates. You may notice that the tool doesn’t even list the total load time, and that’s because it rarely matters for user experience.


Source: Smashing Magazine

A Beginner’s Guide to Webpack 4 and Module Bundling

A squeezing machine that compresses all web elements

Webpack is a module bundler

Webpack has become one of the most important tools for modern web development. Primarily it’s a module bundler for your JavaScript but it can be taught to transform all of your front-end assets like HTML and CSS, even images. It can give you more control over the number of HTTP requests your app is making and allows you to use other flavors of those assets (Jade, Sass & ES6 for example). Webpack also allows you to easily consume packages from npm.

This article is aimed at those who are new to webpack and will cover initial setup and configuration, modules, loaders, plugins, code splitting and hot module replacement. If you find video tutorials helpful I can highly recommend Glen Maddern’s Webpack from First Principles as a starting point to understand what it is that makes webpack special.

To follow along at home you’ll need to have Node.js installed. You can also download the demo app from our Github repo.

Setup

Let’s initialize a new project with npm and install webpack:

mkdir webpack-demo
cd webpack-demo
npm init -y
npm install webpack@beta --save-dev
mkdir src
touch index.html src/app.js webpack.config.js

Edit these files:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello webpack</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="dist/bundle.js"></script>
  </body>
</html>
// src/app.js
const root = document.querySelector('#root')
root.innerHTML = `<p>Hello webpack.</p>`
// webpack.config.js
const path = require('path')

const config = {
  context: path.resolve(__dirname, 'src'),
  entry: './app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [{
      test: /.js$/,
      include: path.resolve(__dirname, 'src'),
      use: [{
        loader: 'babel-loader',
        options: {
          presets: [
            ['es2015', { modules: false }]
          ]
        }
      }]
    }]
  }
}

module.exports = config

The config above is a common starting point, it instructs webpack to compile our entry point src/app.js into our output /dist/bundle.js and all .js files will be transpiled from ES2015 to ES5 with Babel.

To get this running we’re going to need to install three packages, babel-core, the webpack loader babel-loader and the preset babel-preset-es2015 for the flavor of JavaScript we want to write. { modules: false } enables Tree Shaking to remove unused exports from your bundle to bring down the file size.

npm install babel-core babel-loader babel-preset-es2015 --save-dev

Lastly, replace the scripts section of package.json with the following:

"scripts": {
  "start": "webpack --watch",
  "build": "webpack -p"
},

Running npm start from the command line will start webpack in watch mode which will recompile our bundle whenever a .js file is changed in our src directory. The output in the console tells us about the bundles being being created, it’s important to keep an eye on the number of bundles and the size.

Console output of running webpack in watch mode

You should now be able to load index.html in your browser and be greeted with “Hello webpack.”.

open index.html

Open up dist/bundle.js to see what webpack has done, at the top is webpack’s module bootstrapping code and right at the bottom is our module. You may not be colored impressed just yet but if you’ve come this far you can now start authoring ES6 modules and webpack will be able to produce a bundle for production that will work in all browsers.

Stop webpack with Ctrl + C and run npm run build to compile our bundle in production mode.

Notice that the bundle size has come down from 2.61 kB to 585 bytes.
Take another look at dist/bundle.js and you’ll see a big ugly mess of code, our bundle has been minified with UglifyJS, the code will run exactly the same but it’s done with the fewest characters needed.

Modules

Out of the box webpack knows how to consume JavaScript modules in a variety of formats, the most notable two are:

  • ES2015 import statements
  • CommonJS require() statements

We can test this out by installing lodash and importing it from app.js

npm install lodash --save
// src/app.js
import {groupBy} from 'lodash/collection'

const people = [{
  manager: 'Jen',
  name: 'Bob'
}, {
  manager: 'Jen',
  name: 'Sue'
}, {
  manager: 'Bob',
  name: 'Shirley'
}, {
  manager: 'Bob',
  name: 'Terrence'
}]
const managerGroups = groupBy(people, 'manager')

const root = document.querySelector('#root')
root.innerHTML = `<pre>${JSON.stringify(managerGroups, null, 2)}</pre>`

Run npm start to start webpack and refresh index.html, you should see an array of people grouped by manager.

Let’s move the array of people into its own module people.js

// src/people.js
const people = [{
  manager: 'Jen',
  name: 'Bob'
}, {
  manager: 'Jen',
  name: 'Sue'
}, {
  manager: 'Bob',
  name: 'Shirley'
}, {
  manager: 'Bob',
  name: 'Terrence'
}]

export default people

We can simply import it from app.js with a relative path.

// src/app.js
import {groupBy} from 'lodash/collection'
import people from './people'

const managerGroups = groupBy(people, 'manager')

const root = document.querySelector('#root')
root.innerHTML = `<pre>${JSON.stringify(managerGroups, null, 2)}</pre>`

Note: Imports without a relative path like 'lodash/collection' are modules from npm installed to /node_modules, your own modules will always need a relative path like './people', this is how you can tell them apart.

Loaders

We’ve already been introduced to babel-loader, one of many loaders that you can configure to tell webpack what to do when it encounters imports for different file types. You can chain loaders together into a series of transforms, a good way to see how this works is by importing Sass from our JavaScript.

Continue reading %A Beginner’s Guide to Webpack 4 and Module Bundling%


Source: Sitepoint