First impressions are everything, they’re what help us determine if something is worth our time or safe to deal with - Imagine visiting a site that has a popup box as soon as you enter, it wouldn’t only annoy the user, but it would put them off from ever returning.

When it comes to web performance users don’t like to be left waiting and left with a bad impression, so it’s important to refine your site and speed up your web pages. So what defines page speeds? Well it’s broken down into the following:

DNS lookup SSL handshake (if applicable) HTTP response DOM lookup HTML render CSS render JavaScript events

Each point is time spent retrieving, rendering, and executing code, they’re what factor into the time from hitting the enter key in the browser’s address bar to the content appearing on page.

Does Performance Matter?

Of course it does! Have you ever been on a slow site thinking “Gosh, it’s been 5 seconds and nothings loaded, but I’m excited for when it does!”, the answer is a resounding no, so why make your users wait?

Let’s not beat around the bush by over bloating this with performance stats, instead let’s dive straight in and fix these pesky problems!

General

Don’t overkill with plugins

Plugins are great if you’re using a CMS! They help with analytics, search engine optimisation, themes, and a bunch of other cool stuff, but they do have a downside.

The more plugins you have the slower your site is, especially with poorly written code or server intensive plugins that can sometimes cause security issues and crashes.

Everything on your site is there for a reason, so find lightweight quality plugins that get the job done and remove any that don’t.

Minimise HTTP requests

HTTP requests are essentially internet handshakes, they ask for and retrieve data, so the more you have the longer it takes for your page to render.

General tips to reduce HTTP requests:

Combine multiple stylesheets and scripts to reduce the number of files. Use CSS instead of images whenever possible. Combine inline images into your stylesheets to avoid increasing page sizes. Cache content to save on roundtrips to the server with methods like browser caching.

Minify

Every web page is structured and indented so it can be easily read, but this adds to your page size and ultimately affects your user’s load time, not to mention browsers aren’t really down with this sort of thing as ultimately they care about one thing: rendering code.

Minification is the answer as it reads the code, compresses it, and serves it to the browser in a faster and sleeker way, so remember to minify HTML, CSS, and JavaScript whenever possible.

Reduce redirects

Redirects cause additional HTTP requests and add to the overall load time of web pages, for instance sites with a mobile version redirect users from the desktop version to the mobile one, resulting in slower loading assets. In this case a responsive website would be the solution as it eliminates redirects.

Ultimately it all comes down to reducing the number of redirects, so you have less assets being pinged to another location.

Images

Choose the correct file format

Images can be time consuming to grab if unnecessarily big, one factor to consider is the type of file format it’s using as they sometimes contain a bunch of data that isn’t used on the web.

For instance, a JPEG can have Exif metadata from the camera which is the date, model, and location, none of these are used by the browser and are ultimately useless.

The most common file formats are:

PNG (Portable Network Graphics) TIFF (Tagged Image File Format) JPEG/JFIF (Joint Photographic Experts Group File Interchange Format) GIF (Graphic Interchange Format)

For most sites PNG’s are great as it’s a lossless compression file format which is used for illustrations, text, graphs, and logos. JPG’s don’t offer lossless compression, so they should only be used when necessary for things like photos.

Compress your images

There are 2 types of compression: Lossless (no quality degradation) and lossy (quality degradation). It’s favourable to have the former when compressing images, but depending on the file format you’re sometimes stuck. For instance, compressing a JPEG will cause lossy optimisation as they don’t offer lossless compression.

Here’s some useful tools for compressing your images:

Online

Desktop

Don’t rescale images in markup

Define your image’s width and height within the code, this way the browser doesn’t need to render repaints and reflows, so for instance:

<img width="100" height="100" src="logo.jpg" alt="Logo">

This saves the full image being sent and ultimately reduces load time.

Use icon fonts

Icon fonts are a way to reduce the number of http requests sent from the server to end user as it consists of one file, plus they’re super easy to scale as you can change every icon’s size, colour, and opacity in one go.

Icon fonts consist of either of the file formats: SVG, EPS, Ai, PSD, PDF, and also CSS sprites, however browsers grab the first file format and ignore the rest, so it’s best to choose one like SVG when building an icon font.

Custom build your own icon fonts with third-party services:

Alternatively do it yourself by following this guide on Building an SVG Icon Font.

Data URI

Data URI is a technique to inline content like images into CSS so they’re fetched in a single http request rather than multiple, so for instance:

.icon-foobar { background-image: url('foo.png'); }

Would require two requests, one for the CSS file and another for the image, whereas using the data URI technique would not:

.icon-foobar { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRSTlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII%3D'); }

However, don’t use this method is you’re not gzipping your HTML/CSS during http requests as the size overhead can be much larger.

HTML

Styles on top, scripts down below

Stylesheets are the structure of any webpage, without it websites would look like a throwback to 1990’s sites, so it’s important to place CSS at the top of your code within

<head> <meta charset="UTF-8"> <title>CDNify</title> <!-- CSS goes here --> <link rel="stylesheet" href=”style.css" media="all"> </head>

, this way the page is rendered quickly and looks like it loaded faster.

Then there’s scripts like JavaScript which are behavioral, meaning they aren’t needed straight away, plus they slow rendering whilst they’re being loaded and executed. Place scripts at the bottom just before so they’re the last thing parsed:

<body> <p>Speeding up all the things!</p> <!-- JavaScript --> <script src="script.js"></script> </body>

Don’t inline or embed code

You can include CSS or JavaScript in your page using 3 different techniques:

Inline: CSS is defined inside a style attribute and JavaScript inside an onclick attribute. Embedded: CSS is defined inside <style> tags and JavaScript inside <script> tags. External: CSS is loaded from <link> tags and JavaScript from src attributes of <script> tags.

Both inline and embed actually increase the size of your HTML doc, but reduces http requests to external files, so if you have a page where people only visit once then this option will help reduce the number of http requests. Alternatively dump your style and scripts in external files, this way you can improve your code’s structure and the browser can cache individual files if and when needed.

Give async a go

When a script is grabbed the browser has to wait until it’s fully downloaded, parsed, and executed before it’s rendered, all the while your user is left waiting.

<script src="script.js"></script>

Async on the other hand is downloaded asynchronously whilst the rest of the page continues to get parsed, meaning users are free to explore whilst they wait.

<script async src="script.js"></script>

CSS

Combine multiple CSS files

CSS can be split between several files, which is sometimes easier to manage, especially on big projects.

<link rel="stylesheet" href="structure.css" media="all"> <link rel="stylesheet" href="campaign.css" media="all"> <link rel="stylesheet" href="layout.css" media="all">

But this method doesn’t come with it’s downfalls as it requires multiple http requests for each file grabbed. Instead combine CSS into fewer files to reduce the number of requests.

<link rel="stylesheet" href="main.css" media="all">

Alternatively combine them into a single file and automate this process using a build system.

Automated build system

A frontend build system is a way to automate tasks, such as minifying files, optimising images, compiling CSS, and concatenating code to combine it into one file.

There are plenty of automated tools you can use like:

Gulp: Streaming build system Grunt: Task based CMD build tool Bower: Frontend package management Yeoman: Client side stack

Use <link> over @import

You can include an external stylesheet in two ways, using a <link> tag:

<link rel="stylesheet" href="style.css">

Or an @import directive:

@import url('style.css');

An @import is doesn’t allow the browser to download assets at the same time, so it’s better to use a <link> tag.

Minify your CSS

Code should be easy to read and maintainable using proper structure like indents and comments to explain what’s going on.

/* --- Nav Bar --- */ .header { height: 350px; width: 950px; margin: 0 auto; } /* --- Footer --- */ .footer { height: 450px; width: 950px; margin: 0 auto; }

However the browser doesn’t care about this, so it’s important to squish code together to reduce the file size.

.header{height: 350px;width: 950px;margin: 0 auto;}.footer{height: 450px;width: 950px;margin:0 auto;}

Use minification to flatten code which will overall speed up download time, parsing, and execution.

JavaScript

Avoid DOM manipulation

Accessing the DOM is time consuming as it requires manipulation of code, so for example you might want to update:

<div id="container"></div>

With some JavaScript:

<script> var container = document.getElementById("container"); container.innerHTML = "Foo Bar"; </script>

Which will then look like:

<div id="container">Foo Bar</div>

Try to optimise DOM manipulation so you’re not accessing it as much to avoid giving the browser more code to render. For instance, if you’re querying the DOM through a loop, do it once and store the result in a variable, this way you want need to keep accessing the DOM and slowing the browser.

Minimise repaints and reflows

Repaints and reflows are when changes are made to the DOM, causing it to be re-rendered, for example a repaint occurs when changing an element and a reflow is triggered when the page layout is changed.

Setting a width to a style, like style.width, will force the browser to think about the layout to make changes and ultimately slow it down. If you need to make changes like this then do so all at once, this way the browser won’t need to re-render objects.

Use 3rd party content asynchronously

When it comes to 3rd party content it isn’t always packed in the most efficient way, sometimes it can be in jumbles which can then slow down your pages, or worse if it’s hosted on a 3rd party server that’s blocked by your user’s connection.

It’s best to always load 3rd party content asynchronously, this way the entire page won’t slow to a crawl or lock.

var script = document.createElement('script'), scripts = document.getElementsByTagName('script')[0]; script.async = true; script.src = url; scripts.parentNode.insertBefore(script, scripts);

If you have multiple scripts that you want loading asynchronously then use:

(function() { var script, scripts = document.getElementsByTagName('script')[0]; function load(url) { script = document.createElement('script'); script.async = true; script.src = url; scripts.parentNode.insertBefore(script, scripts); } load('//apis.google.com/js/plusone.js'); load('//platform.twitter.com/widgets.js'); load('//s.thirdpartywidget.com/widget.js'); }());

Cache array lengths

With every piece of code there’s usually a more efficient way to store, retrieve, and execute it. One way to handle loop arrays better is to store their size within the cache, this way it doesn’t get recalculated on each loop.

var loopArray = new Array(100), len, i; for (i = 0; i < loopArray.length; i++) { // :( - Array size is recalculated 100 times } for (i = 0, len = loopArray.length; i < len; i++) { // :) - Array size is calculated once and then stored in cache }

Ditch document.write

Let’s get this out there: document.write is a bad practice! It’s a dependency to the page that forces the entire content to be re-written, however it’s still needed as a synchronous fallback for some JavaScript files, so try to avoid it whenever possible.

For instance the following will show “world!” and not “hello world!” as it’s ran after the content is loaded using the window.onload event.

<span>hello </span> <script> window.onload = function() { document.write('<span>world!</span>'); }; </script>

If you can, try to avoid document.write altogether by using a different method.

Minify your JavaScript

CSS isn’t the only one that needs to be minified as JavaScript has a structure and comments that can over bloat it’s file size, as for instance:

MyJavaScript.app = function() { var foo = true; return { bar: function() { // stuff happens } }; };

When it comes to structure and comments, the browser doesn’t care as it processes and renders code regardless. Minifying your code saves file size which improves downloads, parsing, and execution by squishing it all together.

MyJavaScript.app=function(){var a=!0;return{bar:function(){}}}

Combine multiple JavaScript files

Much like CSS, JavaScript can be split into several files, which is often easier to manage when it comes to big projects or working in large organisations.

<script src="navbar.js"></script> <script src="component.js"></script> <script src="page.js"></script> <script src="framework.js"></script> <script src="plugin.js"></script>

However, this method doesn’t come with it’s disadvantages as it requires multiple http requests for each file grabbed. Instead, combine JavaScript into fewer files to reduce the number of requests.

<script src="main.js"></script>

Alternatively combine them into a single file and automate this process using a build system.

jQuery

Grab the latest jQuery version

Third-party code like jQuery is always kept up-to-date to fix bugs, add new functionality, readability, and optimise algorithms, so it’s essential to grab the latest version.

Always grab the latest version using:

https://code.jquery.com/jquery-latest.js

However there might be conflicts between the latest version and your code, if this is the case then reference the last version that was stable with your code:

https://code.jquery.com/jquery-1.11.1.min.js

Selectors

There are many different ways to grab an element from the DOM, such as classes, IDs, or using methods like find() and children(), however the most affective way it to use selectors, this is because it’s based on a native DOM operation:

$("#selector");

When it comes to the DOM always try to optimise grabbing data as it’s time consuming flicking through the DOM tree.

jQuery performance pitfalls

jQuery is a JavaScript library designed to simplify client-side scripting of HTML, but it comes with a price. Libraries tend to be slower as they run alongside the program, so native JavaScript is usually faster than jQuery’s, so instead of using something like jQuery.each, use JavaScript’s native for loop:

for ( var i = 0, len = a.length; i < len; i++ ) { e = a[i]; }

When it comes to deciding which to choose, jQuery or JavaScript, think which you would sacrifice: ease of use or performance.