Making a website page load faster is, at least in part, a question of page size. Page size, in turn, is a function of how much code and content you have in a web document. Content you can always reduce by editing and tightening up your writing, reducing the number of words on each page; code you reduce by eliminating redundant, optional, or unnecessary markup, CSS, or scripts. Every character that you can remove from your page saves you a byte on the final file size. While this may make only a fractional difference to an individual visitor, it really adds up over hundreds or thousands of page views, and becomes especially important if you are paying for your site hosting per download.
There are a number of tools that can “minify” HTML. However, you can start the process as you write the code, especially if you are writing HTML5. Since HTML5 minifiers are still in their infancy, this is a step that you must often take for yourself.
- The following closing tags are optional in HTML5, and can be dropped.
</p>(in most cases),
- (Note that many tools, such as DreamWeaver, will needlessly auto-complete and close your code by default, meaning you will have to use find-and-replace to remove these tags after the page is complete):
- Attribute values only need to use quotations if the value contains spaces or some non-alphanumeric characters (such as a question mark). So
<div id=wrapper>is legitimate, as is
<img src=assets/images/falls.jpg …>but
<img alt=Angel Falls …>is not. (Note that DreamWeaver, etc will automatically quote all attribute values by default).
- You can shorten external links by dropping optional parts of the URL and eliminating the
http:at the start. So
- Avoid unnecessary classes and ids: try to use CSS that does not require additions to your markup, such as descendant, attribute and adjacent selectors.
- Replace divs with classes and ids with appropriate HTML5 semantic containers.
- Remember that HTML5 does not require self-closing tags. So there’s no need for
<hr />: instead, use
- Replace HTML entities with appropriate UTF-8 characters, where possible: for example, replace
- Remove carriage returns and newlines from your code. (This is often easier with a minify application.) If your content is in MySQL, you can use a SELECT:
UPDATE table SET field = REPLACE(field,'\n', '') UPDATE table SET field = REPLACE(field,'\r', '')
You’ll probably want to keep a version of your page with returns still in place, to make editing easier.
At the end of this process, you can easily save 15 – 20% on your HTML file size.
Photograph by leg0fenris, used under a Creative Commons Attribution-NonCommercial-NoDerivs 2.0 Generic license
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.