Advertisement

15+ Tips to Speed Up Your Website, and Optimize Your Code!

by

Once you've been coding for a while, you begin to take something for granted. You forget just how smart you really are. How many hundreds of keyboard shortcuts have we memorized? How many languages have we learned? How many frameworks? How many hacks? To say that web design/development is an extremely tough industry is putting it lightly. Next, add in the fact that much of what you know today will be considered obsolete in a few years.

Today, we'll be looking at a crop of tips and tricks that will help beginners speed up their development time, and code more efficiently. You'll see a mix of quick time savings tips, as well as specific coding tricks to increase your web application's efficiency.

Compress Your Images Even Further

compress images

When using the "Save for Web" tool in Photoshop, we can compress our images in order to lower their respective file sizes. But, did you know that the compression can be taken even further without sacrificing quality? A site named Smush.It makes the process a cinch.

How is This Possible?

The team at Smush.It use a variety of tools.

  • ImageMagick to identify the image type and to convert GIFs to PNG.
  • pngcrush to strip unneeded chunks from PNGs. We're currently experimenting with other PNG tools such as pngout, optipng, pngrewrite that will allow for even better png optimization.
  • jpegtran to strip all meta data from JPEGs (currently disabled) and try progressive JPEGs.
  • gifsicle to optimize GIF animations by striping repeating pixels in different frames.

* The list items above were taken from the SmushIt FAQ Page .

So, just before deploying a new website, run your url through their service to reduce all of your images - thus speeding up your website. Beware - the service may convert your GIF files to PNG. You might need to update your HTML and CSS files accordingly. While we're on the subject, 99% of the time, saving as a PNG is the better decision. Unless you're using a tacky animated GIF, consider the PNG format to be best practice.

Be Wise. Use Snippets.

snippets

Many IDEs offer a "code snippet" panel that will allow you to save code for later use. Do you find yourself visiting lipsum.com too often to grab the generic text? Why not just save it as a snippet? In Dreamweaver, press "Shift F9" to open the snippet tab. You can then drag the appropriate snippet into the appropriate location. This features saves me SO much time over the course of a week.

Utilize Console.log() to Debug

console.log

You've downloaded the jQuery library, and you're slowly trying to grasp the syntax. Along the way, you hit a snag and realize that you can't figure out what the value of $someVariable is equal to. Easy, just do...

console.log($someVariable);

Now, load up Firefox - make sure you have FireBug installed - and press F12. You'll be presented with the correct value.

Now - multiply this by infinity and take it to the depths of forever and you still won't realize how useful Firebug and console.log() can be. :)

Download the Web Developer Toolbar

web developer toolbar

Created by Chris Pederick, this unbelievably helpful Firefox plugin presents you with a plethora of options. Many of you who watch my screencasts know that I'm a fan of using the "Edit CSS" option to adjust my styles in real-time. Other helpful options include...

  • Easily disable Javascript
  • Easily disable CSS
  • Quick HTML/CSS validation links
  • Rulers
  • Disable cookies
  • Too many great features to list!

Web Developer Toolbar

Consider Placing Script Tags at the Bottom

snippets

This is a procedure that we all don't perform enough. Though not always feasible, you can many times speed up your website by placing your script tags next to the closing <body> tag.

....
<script type="text/javascript" src="someScript.js"></script>
<script type="text/javascript" src="anotherScript.js"></script>
</body>

Why Does This Help?

Most current browsers can download a maximum of two components in parallel for each host name. However, when downloading a script, no other downloads can occur. That download must finish before moving forward.

So, when feasible, it makes perfect sense to move these files to the bottom of your document in order to allow the other components (images, css, etc) to load first.

When Deploying, Compress CSS and Javascript Files

compress files

If perfomance is paramount for your website, I strongly suggest that you consider compressing your CSS and Javascript files just before deployment. Don't bother doing it at the beginning of your development. It'll only cause more frustration than help. However, once the bow has been tied, compress those babies up.

Javascript Compression Services

CSS Compression Services

Two other helpful tools for packing JavaScript code are YUI Compressor, and JSMin.

Additionally, you have the option of compressing your HTML - though I wouldn't recommend it. The file reduction is negligible.

jQuery "Quick Tip" Roundup

jQuery Tips

Not too long ago, Jon Hobbs-Smith from tvidesign.co.uk posted a fantastic article that details 25 jQuery tips. Be sure to bookmark this page! Here are several of my favorites.

Check if an element exists.

if ($('#myDiv).length) {  
  // this code will only run if the div with an id of #myDiv exists. 
}

Use a Context

Many people don't realize that, when accessing dom elements, the jQuery function accepts a second parameter - "context". Consider the following...

var myElement = $('#someElement');

This code will require jQuery to traverse the entire DOM. We can improve the speed by using a context as the second parameter.

var myElement = $('#someElement', $('.someContainer'));

Now we're telling jQuery to only search within the .someContainer element, and to ignore everything outside of it.

Use IDs Instead of Classes

When accessing IDs with jQuery, the library uses the traditional "getElementById" method. However, when accessing classes, jQuery must use its own methods to traverse the dom (there isn't a native "getElementByClass" method). As a result, it takes a bit longer!

Review All 25 Tips!

Use $_GET instead of $_POST, if Possible

querystrings

If you have the choice between $_GET or $_POST when making AJAX calls, choose the former.

"The Yahoo! Mail team found that when using XMLHttpRequest, POST is implemented in the browsers as a two-step process: sending the headers first, then sending data. So it's best to use GET, which only takes one TCP packet to send (unless you have a lot of cookies)." - Developer.Yahoo.com

Remember - don't blindly use $_GET. Make sure you know exactly what you're doing first. For example, under no circumstances should you mix the querystring and database access. Not too long ago, one of my Twitter buddies sent me an image of a live website containing a MYSQL query in the url. DON'T DO THIS! :)

When Practical, Use Libraries and Frameworks

use frameworks

Whether you're using PHP, ASP.NET, Mootools, jQuery - or a combination of all of them, consider using frameworks when appropriate.

For example:

  • if I'm running a simple static website and only need a small bit of Javascript to create a rollover effect, importing the jQuery script will be inappropriate.
  • If the most complicated feature of my static website is pulling in an XML file, I don't need to use a framework. In such instances, my site will suffer and cost me more money in extra bandwidth expenditures.

However, if I'm building a complicated site that requires a full CMS and complicated data access, I'll take a look at one of my preferred language's frameworks.

Remember - make frameworks work for you; not the other way around. Be smart when making these decisions.

YSlow

ySlow

YSlow is a wonderful service that checks your website to ensure that it's as efficient as possible. The Yahoo Dev team, not too long ago, created a set of guidelines, or best practices, that should be followed when developing - many of which are detailed in this article, actually.

There's a great YSlow screencast that demonstrates many time saving techiques. I highly recommend that you view it when you have the chance.

ySlow

Keyboard Shortcuts. Learn Them!

template

Most experienced designers/developers will agree with me; if I had to go up to the toolbar menu every time I wanted to make a change to my site or design, I'd be lost. I've been using keyboard shortcuts for so long that I don't know the correct location anymore for these commands. I just know that "Shift X" opens the correct panel.

At first, it can seem like wasted knowledge. But, I assure you that it isn't. I recommend that you do a Google search for "X keyboard shortcuts" - where X is equal to your software (i.e. Photoshop). Print the chart out and place it next to your computer. Over the next few weeks, practice touching your mouse as little as possible. This is one thing that separates the pros from the hobbyists.

Create a "New Website" Template

template

Let's face it; not every website needs to be some huge and complicated application. Sometimes, we simply want to display our portfolio - probably most of the time for some! In these instances, why not create a simple "template" that contains everything you need to get started.

Within my template folder, I have nested "JS" and "CSS" folders.

  • The former contains my "DD_belatedPNG.js" file (adds 24 bit transparency to PNGs in IE6).
  • The latter simply contains a blank "default.css" file, and my own custom reset file.

In addition, I have an "index.html(php)" file that contains a few code snippets that I use on most of my projects. It's nothing too fancy, but it saves time!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/default.css" />

<!--[if lt IE 7]>
<script type="text/javascript" src="js/DD_belatedPNG_0.0.7a-min.js"></script>
<![endif]-->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<title>Untitled Document</title>

<script type="text/javascript">
	$(function() {
	
	});
</script>

</head>

<body>

<div id="container">

</div><!--end container-->

</body>
</html>

As you can see, I reference my CSS and Javascript files, link to Google's jQuery file, create the document.ready() jQuery function, and open up the standard "container" div.

It's rather simplistic, but SAVES TIME. So every time you create a new website, simply copy your "template" folder and dig in.

Inline Vs. External

inline and external

Generally speaking, all of your CSS and Javascript should be removed from the page and placed in their own respective external files.

Why Should We Do This?

  • Cleaner code.
  • Separation of presentation and content is crucial.
  • By using external files, the data will be cached for future use. This reduces the HTML file size without causing an additional HTTP request - because of the caching.

If you only have a few basic styles, an exception can be made. In those, and only those instances, it might be beneficial to include them in the HTML page.

Determine if a PHP Script Was Called With Javascript

inline and external

AJAX is all the rage right now - mostly because it's finally become relatively user-friendly, thanks to Javascript libraries. In some instances, you need to have a way to determine if the script was called with Javascript. There are a few days to accomplish this task.

One way would be to append a unique key-value pair with Javascript when sending the POST. You could then use PHP to determine if that particular key exists. If it does, we know that Javascript is enabled.

A better way would be to use a built in PHP feature called "HTTP_X_REQUESTED_WITH". To illustrate...

if isset($_SERVER['HTTP_X_REQUESTED_WITH']) {
  // write some code and rest assured that the Javascript is enabled.
} else {
  // Do something different to compensate for users that have JS turned off.
}

Link to Google's CDN

link to google

Not too long ago, Google began hosting popular scripts such as jQuery. If you're using such a library, it is strongly recommended that you link to Google's CDN rather than using your own script.

AJAX Libraries API

How Come?

  1. Caching: There is a possibility that your users won't need to download the script at all! When a browser sees a request for a file that has already been downloaded onto the user's computer, it recognizes this and returns a "304" response (NOT MODIFIED). For example, let's imagine that one user visits thirty sites that all link to Google's CDN. In this example, the user would only download jQuery once!
  2. Improve Parallelism: I spoke of this in a previous tip. By removing this extra request, the user's browser can download more content in parallel.

Embrace Firefox Extensions

embrace firefox extensions

I'm a huge fan of Google's Chrome. It opens extremely fast and processes Javascript quicker than any other browser - at least for now (I think the latest version of Firefox might have caught up.).

However, you won't see me leaving Firefox any time soon. The number of helpful plugins available for the browser is astounding. Here's a list of my favorites.

embrace firefox extensions

When Helpful, Use an IDE

use an ide

In the same way that it's cool to hate Microsoft right now, it seems that it's popular at the moment for people to attack those who use IDEs when developing. This is just silly.

In many instances, the use of an advanced IDE is paramount - especially when working in OOP languages. Now, if you're simply creating a small HTML template, programs like Notepad++ and Coda will work splendidly. Actually I'd recommend their usage in these instances. Don't add the extra bloat if you don't need it. However, when developing advanced applications, take advantage of an IDE.

That's All Folks!

That should do it for now. Hopefully, a few of these (maybe all of them!) will help to make you a better designer and developer. What are some of your favorite short-cuts? Leave a comment below and let us know!


Advertisement