Building A Node.js Express API To Convert Markdown To HTML

Original Source: https://www.smashingmagazine.com/2019/04/nodejs-express-api-markdown-html/

Building A Node.js Express API To Convert Markdown To HTML

Building A Node.js Express API To Convert Markdown To HTML

Sameer Borate

2019-04-23T12:30:16+02:00
2019-04-23T18:34:13+00:00

Markdown is a lightweight text markup language that allows the marked text to be converted to various formats. The original goal of creating Markdown was of enabling people “to write using an easy-to-read and easy-to-write plain text format” and to optionally convert it to structurally valid XHTML (or HTML). Currently, with WordPress supporting Markdown, the format has become even more widely used.

The purpose of writing the article is to show you how to use Node.js and the Express framework to create an API endpoint. The context in which we will be learning this is by building an application that converts Markdown syntax to HTML. We will also be adding an authentication mechanism to the API so as to prevent misuse of our application.

A Markdown Node.js Application

Our teeny-tiny application, which we will call ‘Markdown Convertor’, will enable us to post Markdown-styled text and retrieve an HTML version. The application will be created using the Node.js Express framework, and support authentication for conversion requests.

We will build the application in small stages — initially creating a scaffold using Express and then adding various features like authentication as we go along. So let us start with the initial stage of building the application by creating a scaffold.

Stage 1: Installing Express

Assuming you’ve already installed Node.js on your system, create a directory to hold your application (let’s call it “markdown-api”), and switch to that directory:

$ mkdir markdown-api
$ cd markdown-api

Use the npm init command to create a package.json file for your application. This command prompts you for a number of things like the name and version of your application.

For now, simply hit Enter to accept the defaults for most of them. I’ve used the default entry point file as index.js, but you could try app.js or some other depending on your preferences.

Now install Express in the markdown-api directory and save it in the dependencies list:

$ npm install express –save

Create an index.js file in the current directory (markdown-api) and add the following code to test if the Express framework is properly installed:

Const express = require(‘express’);
var app = express();

app.get(‘/’, function(req, res){
res.send(‘Hello World!’);
});

app.listen(3000);

Now browse to the URL http://localhost:3000 to check whether the test file is working properly. If everything is in order, we will see a Hello World!’ greeting in the browser and we can proceed to build a base API to convert Markdown to HTML.

Stage 2: Building A Base API

The primary purpose of our API will be to convert text in a Markdown syntax to HTML. The API will have two endpoints:

/login
/convert

The login endpoint will allow the application to authenticate valid requests while the convert endpoint will convert (obviously) Markdown to HTML.

Below is the base API code to call the two endpoints. The login call just returns an “Authenticated” string, while the convert call returns whatever Markdown content you submitted to the application. The home method just returns a ‘Hello World!’ string.

const express = require(“express”);
const bodyParser = require(‘body-parser’);

var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get(‘/’, function(req, res){
res.send(‘Hello World!’);
});

app.post(‘/login’, function(req, res) {
res.send(“Authenticated”);
},
);

app.post(“/convert”, function(req, res, next) {
console.log(req.body);
if(typeof req.body.content == ‘undefined’ || req.body.content == null) {
res.json([“error”, “No data found”]);
} else {
res.json([“markdown”, req.body.content]);
}
});

app.listen(3000, function() {
console.log(“Server running on port 3000”);
});

We use the body-parser middleware to make it easy to parse incoming requests to the applications. The middleware will make all the incoming requests available to you under the req.body property. You can do without the additional middleware but adding it makes it far easier to parse various incoming request parameters.

You can install body-parser by simply using npm:

$ npm install body-parser

Now that we have our dummy stub functions in place, we will use Postman to test the same. Let’s first begin with a brief overview of Postman.

Postman Overview

Postman is an API development tool that makes it easy to build, modify and test API endpoints from within a browser or by downloading a desktop application (browser version is now deprecated). It has the ability to make various types of HTTP requests, i.e. GET, POST, PUT, PATCH. It is available for Windows, macOS, and Linux.

Here’s a taste of Postman’s interface:

Postman interface

(Large preview)

To query an API endpoint, you’ll need to do the following steps:

Enter the URL that you want to query in the URL bar in the top section;
Select the HTTP method on the left of the URL bar to send the request;
Click on the ‘Send’ button.

Postman will then send the request to the application, retrieve any responses and display it in the lower window. This is the basic mechanism on how to use the Postman tool. In our application, we will also have to add other parameters to the request, which will be described in the following sections.

Using Postman

Now that we have seen an overview of Postman, let’s move forward on using it for our application.

Start your markdown-api application from the command-line:

$ node index.js

To test the base API code, we make API calls to the application from Postman. Note that we use the POST method to pass the text to convert to the application.

The application at present accepts the Markdown content to convert via the content POST parameter. This we pass as a URL encoded format. The application, currently, returns the string verbatim in a JSON format — with the first field always returning the string markdown and the second field returning the converted text. Later, when we add the Markdown processing code, it will return the converted text.

Stage 3: Adding Markdown Convertor

With the application scaffold now built, we can look into the Showdown JavaScript library which we will use to convert Markdown to HTML. Showdown is a bidirectional Markdown to HTML converter written in Javascript which allows you to convert Markdown to HTML and back.

Testing with Postman

(Large preview)

Install the package using npm:

$ npm install showdown

After adding the required showdown code to the scaffold, we get the following result:

const express = require(“express”);
const bodyParser = require(‘body-parser’);
const showdown = require(‘showdown’);

var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

converter = new showdown.Converter();

app.get(‘/’, function(req, res){
res.send(‘Hello World!’);
});

app.post(‘/login’, function(req, res) {
res.send(“Authenticated”);
},
);

app.post(“/convert”, function(req, res, next) {
if(typeof req.body.content == ‘undefined’ || req.body.content == null) {
res.json([“error”, “No data found”]);
} else {
text = req.body.content;
html = converter.makeHtml(text);
res.json([“markdown”, html]);
}
});

app.listen(3000, function() {
console.log(“Server running on port 3000”);
});

The main converter code is in the /convert endpoint as extracted and shown below. This will convert whatever Markdown text you post to an HTML version and return it as a JSON document.


} else {
text = req.body.content;
html = converter.makeHtml(text);
res.json([“markdown”, html]);
}

The method that does the conversion is converter.makeHtml(text). We can set various options for the Markdown conversion using the setOption method with the following format:

converter.setOption(‘optionKey’, ‘value’);

So, for example, we can set an option to automatically insert and link a specified URL without any markup.

converter.setOption(‘simplifiedAutoLink’, ‘true’);

As in the Postman example, if we pass a simple string (such as Google home http://www.google.com/) to the application, it will return the following string if simplifiedAutoLink is enabled:

<p>Google home <a href=”http://www.google.com/”>http://www.google.com/</a></p>

Without the option, we will have to add markup information to achieve the same results:

Google home <http://www.google.com/>

There are many options to modify how the Markdown is processed. A complete list can be found on the Passport.js website.

So now we have a working Markdown-to-HTML converter with a single endpoint. Let us move further and add authentication to have application.

Stage 4: Adding API Authentication Using Passport

Exposing your application API to the outside world without proper authentication will encourage users to query your API endpoint with no restrictions. This will invite unscrupulous elements to misuse your API and also will burden your server with unmoderated requests. To mitigate this, we have to add a proper authentication mechanism.

We will be using the Passport package to add authentication to our application. Just like the body-parser middleware we encountered earlier, Passport is an authentication middleware for Node.js. The reason we will be using Passport is that it has a variety of authentication mechanisms to work with (username and password, Facebook, Twitter, and so on) which gives the user the flexibility on choosing a particular mechanism. A Passport middleware can be easily dropped into any Express application without changing much code.

Install the package using npm.

$ npm install passport

We will also be using the local strategy, which will be explained later, for authentication. So install it, too.

$ npm install passport-local

You will also need to add the JWT(JSON Web Token) encode and decode module for Node.js which is used by Passport:

$ npm install jwt-simple

Strategies In Passport

Passport uses the concept of strategies to authenticate requests. Strategies are various methods that let you authenticate requests and can range from the simple case as verifying username and password credentials, authentication using OAuth (Facebook or Twitter), or using OpenID. Before authenticating requests, the strategy used by an application must be configured.

In our application, we will use a simple username and password authentication scheme, as it is simple to understand and code. Currently, Passport supports more than 300 strategies which can be found here.

Although the design of Passport may seem complicated, the implementation in code is very simple. Here is an example that shows how our /convert endpoint is decorated for authentication. As you will see, adding authentication to a method is simple enough.

app.post(“/convert”,
passport.authenticate(‘local’,{ session: false, failWithError: true }),
function(req, res, next) {
// If this function gets called, authentication was successful.
// Also check if no content is sent
if(typeof req.body.content == ‘undefined’ || req.body.content == null) {
res.json([“error”, “No data found”]);
} else {
text = req.body.content;
html = converter.makeHtml(text);
res.json([“markdown”, html]);
}},
// Return a ‘Unauthorized’ message back if authentication failed.
function(err, req, res, next) {
return res.status(401).send({ success: false, message: err })
});

Now, along with the Markdown string to be converted, we also have to send a username and password. This will be checked with our application username and password and verified. As we are using a local strategy for authentication, the credentials are stored in the code itself.

Although this may sound like a security nightmare, for demo applications this is good enough. This also makes it easier to understand the authentication process in our example. Incidentally, a common security method used is to store credentials in environment variables. Still, many people may not agree with this method, but I find this relatively secure.

The complete example with authentication is shown below.

const express = require(“express”);
const showdown = require(‘showdown’);
const bodyParser = require(‘body-parser’);
const passport = require(‘passport’);
const jwt = require(‘jwt-simple’);
const LocalStrategy = require(‘passport-local’).Strategy;

var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

converter = new showdown.Converter();

const ADMIN = ‘admin’;
const ADMIN_PASSWORD = ‘smagazine’;
const SECRET = ‘secret#4456’;

passport.use(new LocalStrategy(function(username, password, done) {
if (username === ADMIN && password === ADMIN_PASSWORD) {
done(null, jwt.encode({ username }, SECRET));
return;
}
done(null, false);
}));

app.get(‘/’, function(req, res){
res.send(‘Hello World!’);
});

app.post(‘/login’, passport.authenticate(‘local’,{ session: false }),
function(req, res) {
// If this function gets called, authentication was successful.
// Send a ‘Authenticated’ string back.
res.send(“Authenticated”);
});

app.post(“/convert”,
passport.authenticate(‘local’,{ session: false, failWithError: true }),
function(req, res, next) {
// If this function gets called, authentication was successful.
// Also check if no content is sent
if(typeof req.body.content == ‘undefined’ || req.body.content == null) {
res.json([“error”, “No data found”]);
} else {
text = req.body.content;
html = converter.makeHtml(text);
res.json([“markdown”, html]);
}},
// Return a ‘Unauthorized’ message back if authentication failed.
function(err, req, res, next) {
return res.status(401).send({ success: false, message: err })
});

app.listen(3000, function() {
console.log(“Server running on port 3000”);
});

A Postman session that shows conversion with authentication added is shown below.

Final application testing with Postman

Final application testing with Postman (Large preview)

Here we can see that we have got a proper HTML converted string from a Markdown syntax. Although we have only requested to convert a single line of Markdown, the API can convert a larger amount of text.

This concludes our brief foray into building an API endpoint using Node.js and Express. API building is a complex topic and there are finer nuances that you should be aware of while building one, which sadly we have no time for here but will perhaps cover in future articles.

Accessing Our API From Another Application

Now that we have built an API, we can create a small Node.js script that will show you how the API can be accessed. For our example, we will need to install the request npm package that provides a simple way to make HTTP requests. (You will Most probably already have this installed.)

$ npm install request –save

The example code to send a request to our API and get the response is given below. As you can see, the request package simplifies the matter considerably. The markdown to be converted is in the textToConvert variable.

Before running the following script, make sure that the API application we created earlier is already running. Run the following script in another command window.

Note: We are using the (back-tick) sign to span multiple JavaScript lines for the textToConvert variable. This is not a single-quote.

var Request = require(“request”);

// Start of markdown
var textToConvert = `Heading
=======
## Sub-heading

Paragraphs are separated
by a blank line.

Two spaces at the end of a line
produces a line break.

Text attributes _italic_,
**bold**, ‘monospace’.
A [link](http://example.com).
Horizontal rule:`;

// End of markdown

Request.post({
“headers”: { “content-type”: “application/json” },
“url”: “http://localhost:3000/convert”,
“body”: JSON.stringify({
“content”: textToConvert,
“username”: “admin”,
“password”: “smagazine”
})
}, function(error, response, body){
// If we got any connection error, bail out.
if(error) {
return console.log(error);
}
// Else display the converted text
console.dir(JSON.parse(body));
});

When we make a POST request to our API, we provide the Markdown text to be converted along with the credentials. If we provide the wrong credentials, we will be greeted with an error message.

{
success: false,
message: {
name: ‘AuthenticationError’,
message: ‘Unauthorized’,
status: 401
}
}

For a correctly authorized request, the above sample Markdown will be converted to the following:

[ ‘markdown’,
`<h1 id=”heading”>Heading</h1>
<h2 id=”subheading”>Sub-heading</h2>
<p>Paragraphs are separated by a blank line.</p>
<p>Two spaces at the end of a line<br />
produces a line break.</p>
<p>Text attributes <em>italic</em>,
<strong>bold</strong>, ‘monospace’.
A <a href=”http://example.com”>link</a>.
Horizontal rule:</p>` ]

Although we have hardcoded the Markdown here, the text can come from various other sources — file, web forms, and so on. The request process remains the same.

Note that as we are sending the request as an application/json content type; we need to encode the body using json, hence the JSON.stringify function call. As you can see, it takes a very small example to test or API application.

Conclusion

In this article, we embarked on a tutorial with the goal of learning on how to use Node,js and the Express framework to build an API endpoint. Rather than building some dummy application with no purpose, we decided to create an API that converts Markdown syntax to HTML, which anchors or learning in a useful context. Along the way, we added authentication to our API endpoint, and we also saw ways to test our application endpoint using Postman.

Smashing Editorial
(rb, ra, il)

98% Off: Get the Project Management Certification Bundle for Only $49

Original Source: http://feedproxy.google.com/~r/Designrfix/~3/5fltLL4fyuo/98-off-get-the-project-management-certification-bundle-for-only-49

They say great leaders are born, not made. While there is some truth to that, it isn’t always the case. An effective project manager is a good decision maker, has effective communication skills and strong leadership skills. All of these skills can be learned and harnessed over time. The Project Management Certification Bundle offers some […]

The post 98% Off: Get the Project Management Certification Bundle for Only $49 appeared first on designrfix.com.

30+ Useful Chrome Extensions for Web Designers

Original Source: https://www.hongkiat.com/blog/google-chrome-extensions-designers/

A list of most handy Chrome extensions specifically for web designers and developers.

The post 30+ Useful Chrome Extensions for Web Designers appeared first on Hongkiat.

Visit hongkiat.com for full content.

Collective #510

Original Source: http://feedproxy.google.com/~r/tympanus/~3/aYXqTy6zs64/

C510_whatisdesignsys

What is a Design System?

Varun Vachhar and Catherine Maritan take the conversation of Design Systems past style guides and component libraries and get into breaking down silos between development and design.

Read it

overview-bottom

Our Sponsor
Divi: Build Anything Visually

Divi is powered by the Divi Builder, an insanely fast and incredibly intuitive front end editor like nothing you have seen before. It will change the way you build websites forever.

Try it

C510_Glicky

Glicky

Glicky is an in-browser task runner for modern web development.

Check it out

C510_svelte

Svelte 3: Rethinking reactivity

Read all about the new Svelte 3, the component framework that runs at build time.

Read it

C510_commit

Commit messages guide

A guide to understanding the importance of commit messages and how to write them well.

Read it

C510_3dscan

Only CSS: 3D Scan

A stunning demo of a 3D scan animation made only with CSS. By Yusuke Nakaya.

Check it out

C510_names

Inclusively Hidden

Scott O’Hara highlights the methods of hiding content that are most appropriate for modern web development, and notes the accessibility impacts of each.

Read it

C510_figma

Sketch vs Figma, Adobe XD, And Other UI Design Applications

Ashish Bogawat summarizes the unique features of the new Sketch alternatives.

Read it

C510_mockit

MockIt

MockIt gives you an interface to configure and create mock APIs for your applications.

Check it out

C510_cors

CORS Tutorial: A Guide to Cross-Origin Resource Sharing

Learn all about Cross-Origin Resource Sharing, how it protects you, and how to enable CORS in your applications. By Steve Hobbs.

Read it

C510_TinyMirror

Tiny Mirror

Davy Wybiral made an insane little webcam, right inside of a favicon! Check out the demo.

Check it out

C510_things

Introducing Mozilla WebThings

Ben Francis introduces Mozilla WebThings, an open platform for monitoring and controlling devices over the web.

Read it

C510_hovercard

Fading out siblings on hover in CSS

Trys Mudford shows how to make a special hover effect with a neat trick.

Read it

C510_christools

Getting started with Javascript – The right tools and resources

Chris Heilman talks about how to get started with Javascript, and where to find the right resources. You can read the transcript here.

Watch it

Screen-Shot-2019-04-22-at-22.47.25

Mouse Trail

Noah Yamamoto explains how to create an artsy mouse trail animation.

Read it

C510_GB

GB Studio

A free and easy to use retro adventure game creator for your favourite handheld video game system.

Check it out

C510_genart

Giving Generative Art Its Due

Jason Bailey writes about Automat und Mensch, a show on the history of generative art.

Read it

C510_names

Naming things to improve accessibility

Hidde de Vries explains how browsers decide on the names for links, form fields, tables and form groups.

Read it

C510_AI4Animation

AI4Animation – for JavaScript & Three.js

A port of the AI4Animation project, for use with Three.js on the web. It explores the possibilities of using artificial intelligence to generate realtime character animations.

Check it out

C510_directionhover

Direction aware hover effect

Tobias Reich made this great hover effect that starts from where you hover with the mouse.

Check it out

C510_rotatedoverlays

From Our Blog
How to Create and Animate Rotated Overlays

A tutorial on how to create and animate rotated overlays, or “reveal” elements, for interesting page transition effects.

Read it

Collective #510 was written by Pedro Botelho and published on Codrops.

20 Freshest Web Designs, April 2019

Original Source: https://www.webdesignerdepot.com/2019/04/20-freshest-web-designs-april-2019/

Welcome to our roundup of the best new sites to be launched (or relaunched with significant updates) in the last four weeks.

After last month’s flirtation with monochrome, this month’s set of sites return to the overriding trend of 2019: color. Huge images are still popular, and parallax is still finding its way into our scrolling experiences. Enjoy!

Middle Fork Rapid Transit

Middle Fork Rapid Transit is an adventure vacation company that transports you over 100 miles down the Middle Fork river in Idaho. Its site packs in as much as one of its trips, and there’s tons of little details to get you fired up; I love the animated raft, and the grub looks amazing.

To Taste

To Taste is my favorite recipe site of the moment. Packed with food ideas for every occasion and palette, the simple site is laid out perfectly for browsing, and choosing something to make is a culinary treat. What really makes it, as with all food sites, is the mouth-watering photography.

The Face

Style bible The Face returned from oblivion this month, with a new team behind the iconic publication. Its site opens as daringly as you’d expect, before slowing to a more traditional, and more usable blog format.

Kia ProCeed

The site for the new Kia ProCeed is precisely the type of site we used to build back in the day. With interactive video, a unique navigation system based on established design patterns, and carefully designed usability, it’s an enticing experience.

Hiraeth

Co-founded by Rooney Mara, Hiraeth is a fashion label that produces desirable clothes free from any animal product. Its elegant site exudes quality with generous white space, and an almost Scandinavian minimalism, matching the garments perfectly.

Future of Sustainability

According to some estimates, we have just 12 years until we face not just climate change, but climate breakdown. Future of Sustainability wants to inspire you to change the 2020s, before it’s too late. It communicates a complex, and difficult message engagingly.

Nicholas Jackson

Nicholas Jackson is a New York based designer and art director. His portfolio site is a bold, confident expression of the work he loves to do for clients including Canon, The Wall Street Journal, The NY times, and Siemens.

Mansi

Mansi makes some of the best pasta this side of Naples, and it has an equally delicious website. Dotted throughout the site are pasta shapes, some of them animated, making Mansi’s site the most appropriate exponent of the blob trend I’ve seen to date.

Azab

Azab is an architecture firm with a love of mouse trails. Despite most designers abandoning them more than a decade ago, Azab’s site is built entirely around the path of your mouse on the screen. It’s surprisingly compelling.

Corpus

Corpus is an all-natural, all-vegan company producing deodorants that don’t harm you, or the planet. Its site intriguingly turns a standard e-commerce layout on its head, by presenting products up front, and the traditional hero video, down below.

Calidad Beer

Calidad Beer is a Mexican-style beer, brewed in California. With Levis-worthy art direction, and brand appropriate animation, its site is ideal for an unknown company trying to tap into a saturated market. Constantly reinforced, the brand identity is key here.

DEMO

The Design in Motion Festival, or DEMO for short, takes place in Amsterdam in November, when 80 screens in the central train station will showcase the best motion design work. The site itself features beautiful interactive lettering that Saul Bass would be proud of.

Camille Pawlak

The online portfolio of Camille Pawlak is based around a beautiful central animation that rotates as it transforms into the next project. It’s a simple, but elegant way to navigate between projects, and the work that she’s showcasing is excellent too.

Green Chameleon

Green Chameleon’s site is only temporary, with a full website redesign on the horizon. But with a portfolio like this, packed with parallax effects, and dead simple navigation, I think the Bristol agency should stick with what it’s got.

Flwr

Flwr is a New Zealand based florist with a modern approach. Its site uses text to mask its beautiful photography, creating an intriguing and inviting mini-site. It even embraces the split-screen trend to great effect.

Daly

Daly is a PR agency founded by Alex Daly, from her contacts built helping some of the world’s most successful crowdfund campaigns reach their targets. Its site is bold, colorful, and fun. The period after its name isn’t new, but I love the way it follows you down the page as you scroll.

Pacto Navio

When the finest Cuban rum is introduced to French wine making traditions, you get Pacto Navio. The rum, distilled near Havana, is served by a beautifully art directed site, featuring brand illustrations, and a distinctly Caribbean feeling.

Cheval Blanc

The French have a reputation for refined hospitality, and that trend is reflected in their love of sophisticated web sites. The site for Cheval Blanc is no exception, with a just-right level of parallax scrolling and refined typography.

Staat

Staat is a design agency specializing in event design for some of the world’s best known names. Its site features video case studies of its work, and the site itself takes a step backwards and allows the portfolio to shine.

Festa da Francofonia 2019

The 2019 festival for Francophones, is a festival celebrating the 220 million people worldwide who speak the French language. Celebrated from Morocco to Canada, the event’s site is a colorful, international feeling affair, appropriate for a multi-cultural event.

Add Realistic Chalk and Sketch Lettering Effects with Sketch’it – only $5!

Source

p img {display:inline-block; margin-right:10px;}
.alignleft {float:left;}
p.showcase {clear:both;}
body#browserfriendly p, body#podcast p, div#emailbody p{margin:0;}

Fully-Immersive Brand Identity for The Revolution Hotel

Original Source: http://feedproxy.google.com/~r/abduzeedo/~3/dkWDtybVq2Q/fully-immersive-brand-identity-revolution-hotel

Fully-Immersive Brand Identity for The Revolution Hotel
Fantastic & Experimental Brand Identity for The Revolution Hotel

abduzeedoApr 19, 2019

Adam&Co. is a Boston-based multi-disciplinary creative consultancy founded and led by award-winning creative director, Adam Larson in partnership with executive producer, Allison Doherty. With 20+ years working with clients across nearly every industry, The Revolution Hotel is Adam&Co.’s first fully-immersive brand identity project.

The Revolution presented Adam&Co. the opportunity to build a new, dynamic hotel brand from the ground up, extending their expertise into the physical realm through a multifaceted approach to experiential branding. Adam&Co. created and managed the strategic vision, branding, design, and art curation for the first-of-its-kind, boutique hotel in Boston’s historic South End.

About the Project

Boston has a unique way of defining and breaking convention, dating back to the American Revolution in 1775. It’s rich history is why so many people travel from all over the world, to visit the city that started it all. Adam&Co.’s creative vision for the hotel celebrates the city’s vibrant past and it’s continued efforts toward shaping the future.

Catering to today’s experience-seeking global travelers, The Revolution was built to evoke the city’s revolutionary spirit through the integration of art and installations, showcasing historical figures, innovations, and events specific to Boston, recontextualized and juxtaposed through modern applications, creating a balanced mix of the old and the new. Featured artists include Tristan Eaton, The Individuals Collective, and Adam&Co.

The Revolution was built to evoke the city’s revolutionary spirit through the integration of art…

About The Revolution Hotel

The Revolution boasts a variety of room options, including standard king with private bath, quads and triples with bunk beds and shared bathrooms, and long-term stay lofts with kitchenettes, and oversized bathrooms. The hotel also features a cafe, a gym, a large co-working space with a bar, as well as a forthcoming restaurant with outdoor patio for dining and events.

Also in the works is a proprietary augmented reality app that will allow visitors a chance to navigate the content of the hotel in more depth through curated video content.

The building’s history and architecture became a great source of inspiration when approaching the design of the hotel. An adaptive reuse project, the building itself dates back to the 1880’s when it became one of the first YWCAs in the country, a place dedicated to the empowerment of women. In 1953, a Mid-Century Modern addition was added to serve as a dormitory for young women who were joining the workforce after WWII. The developers, architects and design team all took great care to celebrate its original use as well as to embrace, preserve, and expose its original architecture.

Adam&Co. commissioned world-renown Los Angeles’ street artist Tristan Eaton to create a 65 ft. mural that is the centerpiece of the hotel’s lobby, and the first Boston mural by Tristan. Inspired by the famous murals at the nearby Boston Public Library, and created entirely by freehand spray paint, the mural combines carefully rendered portraits of influential Bostonians with various excerpts of the city’s history, and contributions to pop culture. Tristan also designed custom carpeting that lines the halls of the guest floors.

Here is an exclusive BEHIND THE SCENES VIDEO INTERVIEW WITH TRISTAN EATON  

To celebrate our lineage in science, technology and innovation, Adam&Co. partnered with Boston-based Individuals Collective to create a three-story sculptural installation featuring objects that represent significant inventions from the area. The “Innovation Tower” includes everything from microwaves and car parts, to old computers, microchips, transmitters, telephones, safety razors, Converse sneakers, basketballs, volleyballs, and typewriters.

Additional art throughout the hotel includes custom wallpapers, custom stencil murals, and framed art installations all designed by Adam&Co. Adam&Co.

The Revolution Hotel is the first hotel on the east coast to be managed by the boutique hotel management company Provenance Hotels. It is owned and was developed by the Mount Vernon Company, with Creative Direction provided by Adam&Co., designed in partnership with PCA Architects.

Fully-Immersive Brand Identity

Hotel Photos

Screen Shot 2019 04 09 At 9.35.59 PMHttps   Hypebeast.com Image 2018 12 Revolution Hotel Boston Inside Look Tristan Eaton 5Screen Shot 2019 04 09 At 9.36.40 PM CopyHttps   Hypebeast.com Image 2018 12 Revolution Hotel Boston Inside Look Tristan Eaton 4IMG 9795Screen Shot 2019 04 09 At 9.36.08 PMMerlin 148292406 3c9e80b7 Bcf0 4ed5 B25d C627371aa9c0 SuperJumboIMG 9803000 Garden Level 0810Screen Shot 2019 04 09 At 9.35.33 PMScreen Shot 2019 04 09 At 9.33.49 PMHttps   Hypebeast.com Image 2018 12 Revolution Hotel Boston Inside Look Tristan Eaton 10Https   Hypebeast.com Image 2018 12 Revolution Hotel Boston Inside Look Tristan Eaton 14Https   Hypebeast.com Image 2018 12 Revolution Hotel Boston Inside Look Tristan Eaton 12Https   Hypebeast.com Image 2018 12 Revolution Hotel Boston Inside Look Tristan Eaton 8Https   Hypebeast.com Image 2018 12 Revolution Hotel Boston Inside Look Tristan Eaton 11Https   Hypebeast.com Image 2018 12 Revolution Hotel Boston Inside Look Tristan Eaton 13Screen Shot 2019 04 09 At 9.34.14 PMScreen Shot 2019 04 09 At 9.33.18 PMScreen Shot 2019 04 09 At 9.34.31 PMBunker RoomBunk Beds

Behind the scenes: Art Instalations – tristaneaton.com

09252018 Revolution Hotel 160309252018 Revolution Hotel 036009252018 Revolution Hotel 045609252018 Revolution Hotel 055609252018 Revolution Hotel 153909252018 Revolution Hotel 032309252018 Revolution Hotel 147809252018 Revolution Hotel 014009252018 Revolution Hotel 0616Screen Shot 2019 04 09 At 11.17.01 PM09252018 Revolution Hotel 031709252018 Revolution Hotel 0118Screen Shot 2019 04 09 At 11.18.17 PM09252018 Revolution Hotel 010909252018 Revolution Hotel 814109252018 Revolution Hotel 816546315082 2247083241992961 4481749153050787840 O44522822 2210212819013337 2710343003381170176 N46445253 2247083448659607 8353651321307398144 O
 

Branding

Screen Shot 2019 04 09 At 11.21.25 PMScreen Shot 2019 04 09 At 11.21.34 PMScreen Shot 2019 04 09 At 11.25.52 PMScreen Shot 2019 04 09 At 11.23.12 PMScreen Shot 2019 04 09 At 11.21.55 PMScreen Shot 2019 04 09 At 11.26.39 PMScreen Shot 2018 02 27 At 12.40.39 AM

 

Behind the scenes: Design Process

IMG 0224IMG 0545IMG 0042IMG 3002IMG 4806IMG 0365IMG 6952IMG 6949IMG 1272IMG 3205IMG 6955IMG 5080IMG 5082


How to Create and Animate Rotated Overlays

Original Source: http://feedproxy.google.com/~r/tympanus/~3/p3DSKDxEkMw/

Today we’d like to explore a specific reveal effect with you. If you saw the Crossroads Slideshow a while back, you might have noticed the page transition when the content is shown after an image gets clicked. We call this type of transitions a “reveal” animation because some content is already there while an overlay element animates out, revealing what’s underneath.

To make such an effect is pretty straightforward: simply place an overlay with the same or different color of the page background and animate it out of the viewport; whatever is under it will show. But there are two challenges here: one is if you’d like the overlay itself to have some content which you want to conceal, i.e. which you want to get cut off while hiding it and not simply move along with the parent when animating it out. The other challenge is to add a rotation and guarantee that the overlay covers the whole screen so that no gaps are shown when you move it out. When combining these two effects, things get really interesting.

So let’s tackle these two challenges in this little tip today and show some of the many possibilities for how to use these techniques in a page design.

The demos are kindly sponsored by Northwestern: Earn your MS degree entirely online. If you would like to sponsor one of our demos, find out more here.

Attention: Highly experimental prototyping, please view in a capable browser.

The reveal effect

The beauty of the reveal effect is that the technique is very simple, yet the result is so interesting: take any element that has its overflow set to “hidden” and animate it in some direction, while animating its child in the opposite direction. This creates a “cut off” look, the content appears to be steady in one place, as if we’re animating some kind of clipping mask. Yet we are only translating elements.

Under the hood, you can see what’s happening here:

Reveal_step1.2019-04-18 15_09_21

We simply move a container up. Now, let’s keep the content in place by reversing that movement and translating it in the opposite direction:

Reveal_opposite.2019-04-18 15_09_21

One last step is to add overflow: hidden to the parent:

Reveal_final2019-04-18 15_09_21

And that’s it! Now, if you want to spice things up a bit, you can add a different duration or easing to the reverse element or other animations to the inner elements.

Adding a rotation

The effect becomes a little bit more complicated when we want to add a rotation. When we rotate an element it will create gaps and not cover the background entirely anymore. So we need to make sure that it’s width and height is set in such a way that when rotated, there are no gaps.

Technically, we’re want the (minimum) bounding box of a rotated rectangle.

The following Stackoverflow thread gave us the right formula for our case: How to scale a rotated rectangle to always fit another rectangle

We only need to find the correct width and height, so the following bit is interesting to us:

“When you rotate an axis-aligned rectangle of width w and height h by an angle ɸ, the width and height of the rotated rectangle’s axis-aligned bounding box are:

W = w·|cos ɸ| + h·|sin ɸ|
H = w·|sin ɸ| + h·|cos ɸ|

(The notation |x| denotes an absolute value.)”

Additionally, we have to make sure that we keep the previous structure in place and that we show the content straight. So we need to rotate the content back. To ease our animation and not tinker with calculations we avoid moving the rotated content, but instead we’ll use the resized container for the motion.

In total we will use three containers to achieve all that:

<div class=”content content–first”><!– only rotated –>
<div class=”content__move”><!– resized and moved –>
<div class=”content__reverse”><!– reverse rotation –>
<!– … –>
</div>
</div>
</div>

If you look at the x-ray view of one of the demos, you can see the rotation and calculation of the new width and height:

Revealers_xray

Given this structure, there are really endless possibilities for rotated reveal and overlay animations.

Reveal2.2019-04-18 16_26_24

Think of multiple overlays. Think of matching animations of the elements that are being revealed or the ones that get hidden.

Reveal3.2019-04-18 16_28_20

There’s so much to explore!

Reveal5.2019-04-18 17_56_58

Have a look at our little compilation, we hope you enjoy it!

How to Create and Animate Rotated Overlays was written by Mary Lou and published on Codrops.

The User’s Perspective: Using Story Structure To Stand In Your User’s Shoes

Original Source: https://www.smashingmagazine.com/2019/04/user-perspective-story-structure/

The User’s Perspective: Using Story Structure To Stand In Your User’s Shoes

The User’s Perspective: Using Story Structure To Stand In Your User’s Shoes

John Rhea

2019-04-16T16:00:16+02:00
2019-04-19T16:36:08+00:00

Every user interaction with your website is part of a story. The user—the hero—finds themselves on a journey through your website on the way to their goal. If you can see this journey from their perspective, you can better understand what they need at each step, and align your goals with theirs.

My first article on websites and story structure, Once Upon a Time: Using Story Structure for Better Engagement, goes into more depth on story structure (the frame around which we build the house of a story) and how it works. But here’s a quick refresher before we jump into implications:

The Hero’s Journey

Most stories follow a simple structure that Joseph Campbell in his seminal work, Hero with a Thousand Faces, called the Hero’s Journey. We’ll simplify it to a hybrid of the plot structure you learned in high school and the Hero’s Journey. We’ll then take that and apply it to how a user interacts with a website.

The Hero’s journey begins in the ordinary world. An inciting incident happens to draw the hero into the story. The hero prepares to face the ordeal/climax. The hero actually faces the ordeal. Then the hero must return to the ordinary world, his problem solved by the story.

Once upon a time… a hero went on a journey. (Large preview)

Ordinary World
The ordinary world is where the user starts (their every day) before they’ve met your website.

Inciting Incident/Call To Adventure
Near the beginning of any story, something will happen to the hero that will push (or pull) them into the story (the inciting incident/call to adventure). It will give them a problem they need to resolve. Similarly, a user has a problem they need to be solved, and your website might be just the thing to solve it. Sometimes though, a hero would rather stay in their safe, ordinary world. It’s too much cognitive trouble for the user to check out a new site. But their problem — their call to adventure — will not be ignored. It will drive the user into interacting with your site.

Preparation/Rising Action
They’ve found your website and they think it might work to solve their problem, but they need to gather information and prepare to make a final decision.

The Ordeal/Climax
In stories, the ordeal is usually the fight with the big monster, but here it’s the fight to decide to use your site. Whether they love the video game news you cover or need the pen you sell or believe in the graphic design prowess of your agency, they have to make the choice to engage.

The Road Back/Falling Action
Having made the decision to engage, the road back is about moving forward with that purchase, regular reading, or requesting the quote.

Resolution
Where they apply your website to their problem and their problem is *mightily* solved!

Return With Elixir
The user returns to the ordinary world and tells everyone about their heroic journey.

The User’s Perspective

Seeing the website from the user’s perspective is the most important part of this. The Hero’s Journey, as I use it, is a framework for better understanding your user and their state of mind during any given interaction on your site. If you understand where they are in their story, you can get a clearer picture of where and how you fit in (or don’t) to their story. Knowing where you are or how you can change your relationship to the user will make a world of difference in how you run your website, email campaigns, and any other interaction you have with them.

Numerous unsubscribes might not be a rejection of the product, but that you sent too many emails without enough value. Great testimonials that don’t drive engagement might be too vague or focused on how great you are, not what solutions you solve. A high bounce rate on your sign up page might be because you focused more on your goals and not enough on your users’ goals. Your greatest fans might not be talking about you to their friends, not because they don’t like you, but because you haven’t given them the opportunity for or incentivized the sharing. Let’s look at a few of these problems.

Plan For The Refusal Of The Call To Adventure

Often the hero doesn’t want to engage in the story or the user doesn’t want to expend the cognitive energy to look at another new site. But your user has come to your site because of their call to adventure—the problem that has pushed them to seek a solution—even if they don’t want to. If you can plan for a user’s initial rejection of you and your site, you’ll be ready to counteract it and mollify their concerns.

Follow up or reminder emails are one way to help the user engage. This is not a license to stuff your content down someone’s throat. But if we know that one or even seven user touches aren’t enough to draw someone in and engage them with your site, you can create two or eight or thirty-seven user touches.

Sometimes these touches need to happen outside of your website; you need to reach out to users rather than wait for them to come back to you. One important thing here, though, is not to send the same email thirty-seven times. The user already refused that first touch. The story’s hero rarely gets pulled into the story by the same thing that happens again, but rather the same bare facts looked at differently.

So vary your approach. Do email, social media, advertising, reward/referral programs, and so on. Or use the same medium with a different take on the same bare facts and/or new information that builds on the previous touches. Above all, though, ensure every touch has value. If it doesn’t, each additional touch will get more annoying and the user will reject your call forever.

Nick Stephenson is an author who tries to help other authors sell more books. He has a course called Your First 10K Readers and recently launched a campaign with the overall purpose of getting people to register for the course.

Before he opened registration, though, he sent a series of emails. The first was a thanks-for-signing-up-to-the-email-list-and-here’s-a-helpful-case-study email. He also said he would send you the first video in a three-part series in about five minutes. The second email came six minutes later and had a summary of what’s covered in the video and a link to the video itself. The next day he emailed with a personal story about his own struggles and a link to an article on why authors fail (something authors are very concerned about). Day 3 saw email number four… you know what? Let’s just make a chart.

Day
Value/Purpose
Email #

1
Case Study
1

1
Video 1 of 3
2

2
Personal Story and Why Authors Fail Article
3

3
Video 2 of 3
4

4
Honest discussion of his author revenue and a relevant podcast episode
5

5
Video 3 of 3
6

6
Testimonial Video
7

7
Registration Opens Tomorrow
8

8
Registration Info and a pitch on how working for yourself is awesome
9

By this point, he’s hooked a lot of users. They’ve had a week of high quality, free content related to their concerns. He’s paid it forward and now they can take it to the next level.

I’m sure some people unsubscribed, but I’m also sure a lot more people will be buying his course than with one or even two emails. He’s given you every opportunity to refuse the call and done eight different emails with resources in various formats to pull you back in and get you going on the journey.

I’ve Traveled This Road Before

It takes a lot less work to follow a path than to strike a new one. If you have testimonials, they can be signposts in the wilderness. While some of them can and should refer to the ordeal (things that might prevent a user from engaging with you), the majority of them should refer to how the product/website/thing will solve whatever problem the user set out to solve.

“This article was amazing!” says the author’s mother, or “I’m so proud of how he turned out… it was touch-and-go there for a while,” says the author’s father. While these are positive (mostly), they aren’t helpful. They tell you nothing about the article.

Testimonials should talk about the road traveled: “This article was awesome because it helped me see where we were going wrong, how to correct course, and how to blow our competitor out of the water,” says the author’s competitor. The testimonials can connect with the user where they are and show them how the story unfolded.

This testimonial for ChowNow talks about where they’ve been and why ChowNow worked better than their previous setup.

“Life before ChowNow was very chaotic — we got a lot of phone calls, a lot of mistyped orders. So with ChowNow, the ability to see the order from the customer makes it so streamlined.” John Sungkamee, Owner, Emporium Thai Cuisine

“I struggled with the same things you did, but this website helped me through.” (Large preview)

So often we hear a big promise in testimonials. “Five stars”, “best film of the year,” or “my son always does great.” But they don’t give us any idea of what it took to get where they are, that special world the testifier now lives in. And, even if that company isn’t selling a scam, your results will vary.

We want to trumpet our best clients, but we also want to ground those promises in unasterisked language. If we don’t, the user’s ordeal may be dealing with our broken promises, picking up the pieces and beginning their search all over again.

The Ordeal Is Not Their Goal

While you need to help users solve any problems preventing them from choosing you in their ordeal, the real goal is for them to have their problem solved. It’s easy to get these confused because your ordeal in your story is getting the user to buy in and engage with your site.

Your goal is for them to buy in/engage and your ordeal is getting them to do that. Their goal is having their problem solved and their ordeal is choosing you to solve that problem. If you conflate your goal and their goal then their problem won’t get solved and they won’t have a good experience with you.

This crops up whenever you push sales and profits over customer happiness. Andrew Mason, founder of Groupon, in his interview with Alex Bloomberg on the podcast “Without Fail”, discusses some of his regrets about his time at Groupon. The company started out with a one-deal-a-day email — something he felt was a core of the business. But under pressure to meet the growth numbers their investors wanted (their company goals), they tried things that weren’t in line with the customer’s goals.

Note: I have edited the below for length and clarity. The relevant section of the interview starts at about 29:10.

Alex: “There was one other part of this [resignation] letter that says, ‘my biggest regrets are the moments that I let a lack of data override my intuition on what’s best for our company’s customers.’ What did you mean by that?”

Andrew: “Groupon started out with these really tight principles about how the site was going to work and really being pro customer. As we expanded and as we went after growth at various points, people in the company would say, ‘hey why don’t we try running two deals a day? Why don’t we start sending two emails a day?’ And I think that sounds awful, like who wants that? Who wants to get two emails every single day from a company? And they’d be like, ‘Well sure, it sounds awful to you. But we’re a data driven company. Why don’t we let the data decide?’ …And we’d do a test and it would show that maybe people would unsubscribe at a slightly higher rate but the increase in purchasing would more than make up for it. You’d get in a situation like: ‘OK, I guess we can do this. It doesn’t feel right, but it does seem like a rational decision.’ …And of course the problem was when you’re in hypergrowth like [we were] …you don’t have time to see what is going to happen to the data in the long term. The churn caught up with [us]. And people unsubscribed at higher rates and then before [we] knew it, the service had turned into… a vestige of what it once was.”

— Without Fail, Groupon’s Andrew Mason: Pt. 2, The Fall (Oct. 8, 2018)

Tools For The Return With The Elixir

Your users have been on a journey. They’ve conquered their ordeal and done what you hoped they would, purchased your product, consumed your content or otherwise engaged with you. These are your favorite people. They’re about to go back to their ordinary world, to where they came from. Right here at this pivot is when you want to give them tools to tell how awesome their experience was. Give them the opportunity to leave a testimonial or review, offer a friends-and-family discount, or to share your content.

SunTrust allows electronic check deposit through their mobile app. For a long while, right after a deposit, they would ask you if you wanted to rate their app. That’s the best time to ask. The user has just put money in their account and are feeling the best they can while using the app.

suntrust app check deposit screen

“Money, money, money! Review us please?” (Large preview)

The only problem was is that they asked you after every deposit. So if you had twelve checks to put in after your birthday, they’d ask you every time. By the third check number, this was rage inducing and I’m certain they got negative reviews. They asked at the right time, but pestered rather than nudged and — harkening back to the refusal of the call section — they didn’t vary their approach or provide value with each user touch.

Note: Suntrust has since, thankfully, changed this behavior and no longer requests a rating after every deposit.

Whatever issue you’re trying to solve, the Hero’s Journey helps you see through your user’s eyes. You’ll better understand their triumphs and pain and be ready to take your user interactions to the next level.

So get out there, put on some user shoes, and make your users heroic!

Smashing Editorial
(cc, il)

Collective #509

Original Source: http://feedproxy.google.com/~r/tympanus/~3/k4M5W74SpTg/

C509_WOTW

Inspirational Website of the Week: Greater Than Avatars

A stunning design with great balance and details. Our pick this week.

Get inspired

C509_NW

This content is sponsored via Thought Leaders
Northwestern MS in Information Design and Strategy

Prepare for a range of dynamic communication roles and build the in-demand skills needed to drive user interactions.

Apply Now

C509_trends

Web Design Trends 2019

A very inspirational list of fundamental web design trends for 2019.

Read it

C509_hints

Optimizing Performance With Resource Hints

Learn how you can use Resource Hints to help the browser stay one step ahead of the user in this article by Drew McLellan.

Read it

C509_solar

Solar CSSystem

All the solar system’s planets made with CSS by Rob DiMarzo.

Check it out

C509_diagonal

Diagonal Containers in CSS

A tutorial by Sebastiano Guerriero, where he shows how to create full-width, diagonal sections in CSS using the clip-path property.

Read it

C509_cassie

Limitation Breeds Creativity

Cassie Evans’ great talk at Bytes Conf 2019.

Watch it

C509_3d

js-cloudimage-360-view

A simple, interactive resource that can be used to provide a virtual tour of your product.

Check it out

C509_movingmouse

Simulating Mouse Movement

Louis Hoebregts shows how to simulate a moving mouse using the Simplex noise algorithm.

Read it

C509_notre

Why Notre-Dame Was a Tinderbox

An scrollable WebGL presentation that visualizes why Notre-Dame was all but assured to go up in flames.

Check it out

C509_cube

cube.js

In case you didn’t know about it: Cube.js is an open source modular framework to build analytical web applications.

Check it out

C509_animatedgrid

Animated grid

A hypnotizing animated grid demo made by David A.

Check it out

C509_visualprogram

A graphical introduction to dynamic programming

Avik Das wrote and illustrated this visual introduction to dynamic programming.

Read it

C509_includinghtml

HTML Includes That Work Today

Scott Jehl describes an experimental technique for including another file directly into a page.

Read it

C509_ascii

ASCII WARP GITHUB

Ibrahim Tanyalcin shows how you can use LexiconMonoSeq to animate ASCII.

Check it out

C509_matt

ToneJS + canvas-sketch

An interactive and generative site made with canvas-sketch and Tone.js. By Matt DesLauriers.

Check it out

C509_slideshow

Fullscreen Scroll Slideshow

Yoichi Kobayashi created this useful fullscreen slideshow that works on scroll.

Check it out

C509_solid

Solid Template

Solid is a simple and responsive HTML landing page template for startups.

Check it out

C509_particles

Particles 101

Tibix’s tutorial on how to make animations based on moving particles.

Read it

C509_cssdrone

Only CSS: STARFOX Arwing Drone

Yusuke Nakaya created this stunning CSS-only flying drone demo.

Check it out

C509_url

URL equalizer

So much coding goodness in just a couple of tweets. A realtime favicon waveform follows.

Check it out

C509_nicedoc

Nicedoc.io

Nicedoc.io aims to reduce the documentation friction, converting any markup file hosted on github.com into great looking documentation.

Check it out

C509_pngs

IMGBIN

A place to find free PNG images for your next wild collage.

Check it out

C509_demos3

From Our Blog
Awesome Demos Roundup #3

The third collection of beautiful, creative experiments that we’ve found around the web.

Check it out

Collective #509 was written by Pedro Botelho and published on Codrops.

Optimizing Performance With Resource Hints

Original Source: https://www.smashingmagazine.com/2019/04/optimization-performance-resource-hints/

Optimizing Performance With Resource Hints

Optimizing Performance With Resource Hints

Drew McLellan

2019-04-17T12:30:16+02:00
2019-04-19T15:05:47+00:00

Modern web browsers use all sorts of techniques to help improve page load performance by guessing what the user may be likely to do next. The browser doesn’t know much about our site or application as a whole, though, and often the best insights about what a user may be likely to do come from us, the developer.

Take the example of paginated content, like a photo album. We know that if the user is looking at a photo in an album, the chance of them clicking the ‘next’ link to view the following image in the album is pretty high. The browser, however, doesn’t really know that of all the links on the page, that’s the one the user is most likely to click. To a browser, all those links carry equal weight.

What if the browser could somehow know where the user was going next and could fetch the next page ahead of time so that when the user clicks the link the page load is much, much faster? That’s in principal what Resource Hints are. They’re a way for the developer to tell the browser about what’s likely to happen in the future so that the browser can factor that into its choices for how it loads resources.

All these resource hints use the rel attribute of the <link> element that you’ll be familiar with finding in the <head> of your HTML documents. In this article we’ll take a look at the main types of Resource Hints and when and where we can use them in our pages. We’ll go from the small and subtle hints through to the big guns at the end.

DNS Prefetching

A DNS lookup is the process of turning a human-friendly domain name like example.com into the machine-friendly IP address like 123.54.92.4 that is actually needed in order to fetch a resource.

Every time you type a URL in the browser address bar, follow a link in a page or even load a resource like an image from a different domain, the browser needs to do a DNS lookup to find the server that holds the resource we’ve requested. For a busy page with lots of external resources (like perhaps a news website with loads of ads and trackers), there might be dozens of DNS lookups required per page.

The browser caches the results of these lookups, but they can be slow. One performance optimization technique is to reduce the number of DNS lookups required by organizing resources onto fewer domains. When that’s not possible, you can warn the browser about the domains it’s going to need to look up with the dns-prefetch resource hint.

<link rel=”dns-prefetch” href=”https://images.example.com”>

When the browser encounters this hint, it can start resolving the images.example.com domain name as soon as possible, even though it doesn’t know how it’ll be used yet. This enables the browser to get ahead of the game and do more work in parallel, decreasing the overall load time.

When Should I Use dns-prefetch?

Use dns-prefetch when your page uses resources from a different domain, to give the browser a head start. Browser support is really great, but if a browser doesn’t support it then no harm done — the prefetch just doesn’t happen.

Don’t prefetch any domains you’re not using, and if you find yourself wanting to prefetch a large number of domains you might be better to look at why all those domains are needed and if anything can be done to reduce the number.

Preconnecting

One step on from DNS prefetching is preconnecting to a server. Establishing a connection to a server hosting a resource takes several steps:

DNS lookup (as we’ve just discussed);
TCP handshake
A brief “conversation” between the browser and server to create the connection.
TLS negotiation on HTTPS sites
This verifies that the certificate information is valid and correct for the connection.

This typically happens once per server and takes up valuable time — especially if the server is very distant from the browser and network latency is high. (This is where globally distributed CDNs really help!) In the same way that prefetching DNS can help the browser get ahead of the game before it sees what’s coming, pre-connecting to a server can make sure that when the browser gets to the part of the page where a resource is needed, the slow work of establishing the connection has already taken place and the line is open and ready to go.

<link rel=”preconnect” href=”https://scripts.example.com”>

When Should I Use preconnect?

Again, browser support is strong and there’s no harm if a browser doesn’t support preconnecting — the result will be just as it was before. Consider using preconnect when you know for sure that you’re going to be accessing a resource and you want get ahead.

Be careful not to preconnect and then not use the connection, as this will both slow your page down and tie up a tiny amount of resource on the server you connect to too.

Prefetching The Next Page

The two hints we’ve looked at so far are primarily focussed on resources within the page being loaded. They might be useful to help the browser get ahead on images, scripts or fonts, for example. The next couple of hints are concerned more with navigation and predicting where the user might go after the page that’s currently being loaded.

The first of these is prefetching, and its link tag might look like this:

<link rel=”prefetch” href=”https://example.com/news/?page=2″ as=”document”>

This tells the browser that it can go ahead and fetch a page in the background so that it’s ready to go when requested. There’s a bit of a gamble here because you have to preempt where you think the user will navigate next. Get it right, and the next page might appear to load really quickly. Get it wrong, and you’ve wasted time and resources in downloading something that isn’t going to be used. If the user is on a metered connection like a limited mobile phone plan, you might actually cost them real money.

When a prefetch takes place, the browser does the DNS lookup and makes the server connection we’ve seen in the previous two types of hint, but then goes a step further and actually requests and downloads the files. It stops at that point, however, and the files are not parsed or executed and they are in no way applied to the current page. They’re just requested and kept ready.

You might think of a prefetch as being a bit like adding a file to the browser’s cache. Instead of needing to go out to the server and download it when the user clicks the link, the file can be pulled out of memory and used much quicker.

The as Attribute

In the example above, you can see that we’re setting the as attribute to as="document". This is an optional attribute that tells that browser that what we’re fetching should be handled as a document (i.e. a web page). This enables the browser to set the same sort of request headers and security policies as if we’d just followed a link to a new page.

There are lots of possible values for the as attribute by enabling the browser to handle different types of prefetch in the appropriate way.

Value of as
Type of resource

audio
Sound and music files

video
Video

Track
Video or audio WebVTT tracks

script
JavaScript files

style
CSS style sheets

font
Web fonts

image
Images

fetch
XHR and Fetch API requests

worker
Web workers

embed
Multimedia <embed> requests

object
Multimedia <object> requests

document
Web pages

The different values that can be used to specify resource types with the as attribute.

When Should I Use prefetch?

Again prefetch has great browser support. You should use it when you have a reasonable amount of certainty of the user might follow through your site if you believe that speeding up the navigation will positively impact the user experience. This should be weighed against the risk of wasting resources by possibly fetching a resource that isn’t then used.

Prerendering The Next Page

With prefetch, we’ve seen how the browser can download the files in the background ready to use, but also noted that nothing more was done with them at that point. Prerendering goes one step further and executes the files, doing pretty much all the work required to display the page except for actually displaying it.

This might include parsing the resource for any subresources such as JavaScript files and images and prefetching those as well.

<link rel=”prerender” href=”https://example.com/news/?page=2″>

This really can make the following page load feel instantaneous, with the sort of snappy load performance you might see when hitting your browser’s back button. The gamble is even greater here, however, as you’re not only spending time requesting and downloading the files, but executing them along with any JavaScript and such. This could use up memory and CPU (and therefore battery) that the user won’t see the benefit for if they end up not requesting the page.

When Should I Use prerender?

Browser support for prerender is currently very restricted, with really only Chrome and old IE (not Edge) offering support for the option. This might limit its usefulness unless you happen to be specifically targeting Chrome. Again it’s a case of “no harm, no foul” as the user won’t see the benefit but it won’t cause any issues for them if not.

Putting Resource Hints To Use

We’ve already seen how resource hints can be used in the <head> of an HTML document using the <link> tag. That’s probably the most convenient way to do it, but you can also achieve the same with the Link: HTTP header.

For example, to prefetch with an HTTP header:

Link: <https://example.com/logo.png>; rel=prefetch; as=image;

You can also use JavaScript to dynamically apply resource hints, perhaps in response to use interaction. To use an example from the W3C spec document:

var hint = document.createElement(“link”);
hint.rel = “prefetch”;
hint.as = “document”;
hint.href = “/article/part3.html”;
document.head.appendChild(hint);

This opens up some interesting possibilities, as it’s potentially easier to predict where the user might navigate next based on how they interact with the page.

Things To Note

We’ve looked at four progressively more aggressive ways of preloading resources, from the lightest touch of just resolving DNS through to rending a complete page ready to go in the background. It’s important to remember that these hints are just that; they’re hints of ways the browser could optimize performance. They’re not directives. The browser can take our suggestions and use its best judgement in deciding how to respond.

This might mean that on a busy or overstretched device, the browser doesn’t attempt to respond to the hints at all. If the browser knows it’s on a metered connection, it might prefetch DNS but not entire resources, for example. If memory is low, the browser might again decide that it’s not worth fetching the next page until the current one has been offloaded.

The reality is that on a desktop browser, the hints will likely all be followed as the developer suggests, but be aware that it’s up to the browser in every case.

The Importance Of Maintenance

If you’ve worked with the web for more than a couple of years, you’ll be familiar with the fact that if something on a page is unseen then it can often become neglected. Hidden metadata (such as page descriptions) is a good example of this. If the people looking after the site can’t readily see the data, then it can easily become neglected and drift out of date.

This is a real risk with resource hints. As the code is hidden away and goes pretty much undetected in use, it would be very easy for the page to change and any resource hints to go un-updated. The consequence of say, prefetching a page that you don’t use, means that the tools you’ve put in place to improve the performances of your site are then actively harming it. So having good procedures in place to key your resource hints up to date becomes really, really important.

Resources

“Resource Hints specification,” W3C
“Speed Up Next-Page Navigations With Prefetching,” Addy Osmani

Smashing Editorial
(il)