This article was sponsored by Hosting Facts. Thank you for supporting the sponsors who make SitePoint possible.
You can spend months building an amazing website only to let yourself down at the last stage with inadequate optimization or hosting.
Average page weight has reached 2,300KB and increases around 15% every year. The rise of projects such as Google Accelerated Mobile Pages, Facebook Instant Articles and ad-blockers highlight user frustration with the web we’ve created. Obese pages:
- are slower to load and render
- struggle on mobile networks and may cost users money
- are less responsive on slower devices and smartphones
- will affect your search engine rankings
- are more difficult to update and maintain.
Few developers bother to optimize their sites so why should you?
The reason: there’s no downside. Your search engine rankings improve. Your users benefit from a slicker experience. Your conversions increase. Your hosting charges drop. Unlike real life, the most drastic weight loss can be achieved with minimal effort…
Site Analysis Tools
Assess the scale of any problems before making changes. Several free tools are available which report the number of requests, file sizes and server response speed. Some provide improvement suggestions.
Alternatively, use the Network or Profiling tools in your browser’s development tools to assess your site. Make a copy of the statistics so you can compare improvements later.
The following sections provide optimization suggestions starting with the easiest changes.
Find a Suitable Web Host
Your site may have taken considerable time and money to create. Should you really host it on a $5 per month service?
Take time to assess whether you need space on a shared server, your own private server or a cloud-based virtual server. Read hosting reviews at sites such as Hosting Facts and seek advice from others with similar requirements. At this moment, they’re suggesting to use A2 Hosting or A Small Orange.
Use a Content Delivery Network (CDN)
Browsers limit HTTP requests to between four and eight simultaneous connections per domain. Loading 40 page assets at once is not possible – files are queued on each request thread.
In addition, your users may be located in a different geographical location to your server. A user in France would see a faster response from a UK-based server than similar hardware in Australia.
A CDN increases download speeds by distributing web site assets to other servers. Those machines can be physically closer to the user and run from different domains which more than doubles HTTP request limits.
CDNs have become simpler to use and many automatically handle assets once you’ve configured DNS settings. Popular options include:
Enable GZIP Compression
Around a third of websites do not enable Gzip compression yet it can drastically reduce the amount of data sent to the browser. Gzip compression is often set by your web host on the server – contact them for further advice.
Enable Caching
Caching ensures a browser downloads asset files once. The local version is retained until your website instructs it to fetch an update. The first page load won’t be faster but subsequent page loads will be considerably improved.
There are plugins for Content Management Systems such as WordPress which make caching simple, e.g. W3 Total Cache or WP Super Cache.
Other systems can adopt technologies such as Expires, Last-Modified, Keep-Alive or Etag in the HTTP header. Your host may provide configuration options or you can define your own. For example, an Apache .htaccess setting to cache all images for one month:
<IfModule mod_expires.c>
ExpiresActive On
<FilesMatch "\.(jpg|jpeg|png|gif|svg)$">
ExpiresDefault "access plus 1 month"
</FilesMatch>
</IfModule>
Optimize Your Media
Images account for more than 60% of page weight. The average page requests 55 separate images at 1,457KB, 126KB of fonts, 400KB of video and 45KB of Flash. This seems slightly preposterous given the current trend for simplistic, plain-colored flat-designs!
The first step: remove unnecessary assets. Do you need that background video, hero image, italic font or 300 icons few will ever see? Can you use a subset of a font? Could you replace some images with CSS3 effects such as gradients or borders?
Presuming an image is required, ensure you use the most efficient format. In general:
- SVG is suitable for line diagrams
- Web fonts may be an option for single-color icons
- PNG or perhaps GIF is best for smaller images with clear color definitions such as icons, buttons and screenshots
- JPG is best for photographs or anything where fine detail is less important.
If in doubt, experiment with different types until you find the best compromise between quality and file size.
Large images should be resized to reduce the resolution. An entry-level smartphone camera produces high-resolution photographs of several megabytes but you rarely need an image greater than 2,000 pixels wide for the best of today’s screens.
Next: ensure your images are the optimal size. Few graphics packages remove all possible data and most will retain unnecessary colors or EXIF meta data such as dates, locations and camera settings. One-off compression tasks can be achieved using online tools such as TinyPNG/JPE or smush.it. Installable processing tools such as OptiPNG, PNGOUT, jpegtran and jpegoptim can bulk-compress images. You can introduce compression systems such as imagemin into your build process or CMS users have options such as WP Smush which automatically compress uploaded files.
Smaller images can be combined into a single image sprite to reduce the number of HTTP requests. This has less of an advantage in HTTP/2 but icons used on every page can still benefit from being combined.
Finally, consider Base64-encoded inline data URIs for smaller, regularly-used images, e.g.
.bullet {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC");
}
This reduces the number of requests although maintenance can be more difficult. Online tools such as DataURL.net and data:URI Generator are fine for one-off conversions. There may also be encoder plugins for your editor/IDE but the easiest solution is PostCSS Assets – a PostCSS plugin – which magically converts any image, e.g.
.inline {
background-image: inline('image.png');
}
Concatenate and Minify CSS and JavaScript
The average page loads 360KB of JavaScript distributed over 22 separate files and 76KB of CSS in 8 stylesheets. Some of these may be provided by third-party social media or advertising widgets but your own files can be:
- Concatenated to join all code into a single file to reduce HTTP requests, and
- Minified to remove unnecessary comments and whitespace. More extreme tools can rename variables and functions to shorter alternatives, e.g.
launchWidget()
becomesw()
.
For a simpler graphical interface, a tool such as Koala provides CSS and JavaScript compression options.
Pre-processors such as Sass, LESS and Stylus or build tools including cssnano for PostCSS can optimize CSS whenever you make a change.
JavaScript can be a little more difficult since source order will be critical. You could consider a system such as Browserify to bundle dependencies. I often use a simpler Gulp plugins including:
- gulp-deporder to control dependencies. An optional comment at the top of each source file determines a suitable order, e.g. // requires: config.js, lib.js
- gulp-concat to concatenate to a single file
- gulp-strip-debug to remove console and debugger statements
- gulp-uglify to minify.
HTTP/2 may make some of these techniques redundant if you use different CSS and JavaScript assets on each page but it should still be considered for files which change less frequently.
Remove Unnecessary Code
It is easier to add bulk than remove it but I suspect you could remove half the code from most sites without making a noticeable difference. The main culprits:
CMS Themes and Templates
Most themes are generic to appeal to a wide range of users. You may only use a fraction of the features so check whether a more lightweight alternative is available.
CMS Plugins
Avoid using plugins unless it’s absolutely necessary. In general, front-end plugins such as carousels or widgets are the worst offenders since they often contain separate sets of CSS and JavaScript.
CSS Frameworks
Frameworks such as Bootstrap contains a range of styles – most of which you’ll never use. Tools such as UnCSS can analyze your pages and identify unnecessary rules.
JavaScript Frameworks
Avoid using more than one framework and consider smaller or modular options where possible. You may be able to dump your framework altogether.
JavaScript Effects
Simple effects such as sliding and fading out can be implemented using lightweight CSS3 animations and transformations rather than less efficient JavaScript.
Social Media Widgets
That innocuous like button can carry half a megabyte of hidden code. They are rarely necessary – link is all you require.
Advertising
If you sign up to 57 advertising networks, each will provide their own chunk of code which slows your site. Assess your revenues and drop less profitable widgets.
Further Optimizations
The options above will make a noticeable difference to your website speed without time-consuming changes. Re-run your pages through the tools above to verify the savings and check whether usage and conversions have increased.
For more radical optimizations…
Adopt a Build Process
The most conscientious developer will forget to compress an image or concatenate CSS when it’s a manual task. A build process can automate tedious tasks on the fly; it’s easy to minify JavaScript when it’s done for you whenever you make a change.
The two most popular options are Gulp and Grunt but there are solutions for most languages and systems. The initial set-up will take a little time but your improved workflow will save hours of effort later.
Simplify Your Design
Many modern websites and applications eschew complexity to provide a streamlined, customer-focused experience. Simplification can be difficult and it’s often easier to start the project again. Question all feature requests or demand that a feature is removed for every one you add.
Consider a Static Site
A CMS is overkill for the majority of websites. Few receive more than a couple of updates a week yet a CMS remains running in the background churning out page content which rarely changes. An alternative is a static site generator. These offer many CMS benefits such as templates but generate a series of flat HTML files with better performance, security and reliability.
Change Your Development Lifestyle
There’s little excuse for 2.3MB pages when content rarely exceeds several hundred words. It’s easy to neglect performance when you’re rapidly developing a site for minimal cost. But what is the point when the result is a slow, clunky product no one wants to use?
Plan performance from the start. Your clients may not appreciate the benefits immediately but the long-term rewards of higher rankings and improved engagement will help your project stand out. Consider:
- limiting your connectivity. Access your site in an area with poor mobile coverage or on a crowded public network. Your frustration could be experienced by thousands of users every day.
- assessing weight in every project and question every asset added to the page.
Web page obesity is an epidemic but it’s evident few developers care. Create slimline pages to learn valuable skills which help you retain and gain new clients.
Further reading:
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.