Posts Tagged ‘javascript’

How To Capture And Track Clicks On The Facebook “Like” Button

Tuesday, May 25th, 2010

The Facebook “Like” button is being added to more and more websites. If you also want to add the “Like” button to your website there are two possible options available. You can either use an iframe directly and generate the code on the Facebook website or use Facebook’s own XFBML extensions to HTML.

Because integration of the iframe solution is really straightforward – you can create your iframe code on the Facebook website – this article will only focus on integrating the XFBML solution which although being a bit more complex has the following advantages:

  • allows the user to add a comment as well
  • allows you to track the click on the like button

Obtaining A Facebook Application Id

First of all  have done this you have to obtain an application id (“app id”) from Facebook just as if you were to create a full Facebook app. Go to this site, enter a name for your “application”, e.g. your website domain name, agree to the terms and click on the “Create” button.

On the following page just enter the URL for your website pointing to your homepage, e.g. “http://www.saschakimmel.com/” in the field “COnnect URL”. Just make sure that the URL contains a slash at the end.

After you’ve clicked on the “Save Changes” button Facebook will show you an application id, your secret key and some more information. For the purpose of this article you only need the application id.

Adding The Core Code With Standard JavaScript

After you have obtained the application id you first of all have to add Facebook’s namespace to your html element on the website you wish to add the “Like” button to:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

After this you have to add this code to the page on your website where you wish to add the “Like” button to. Add this add the very end of your HTML code right before the closing “</body>” tag:

<div id="fb-root"></div>
<script type="text/javascript">
<!--
window.fbAsyncInit = function() {
 FB.init({appId: 'YOUR_FACEBOOK_APP_ID', status: true, cookie: true, xfbml: true});
 FB.Event.subscribe('edge.create', function(href, widget) {
 // Do something, e.g. track the click on the "Like" button here
 alert('You just liked '+href);
 });

};
(function() {
 var e = document.createElement('script');
 e.type = 'text/javascript';
 e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
 e.async = true;
 document.getElementById('fb-root').appendChild(e);
 }());
//-->
</script>

As you can see I have highlighted three parts in red. The first one, “YOUR_FACEBOOK_APP_ID” has to be replaced with the Facebook Application Id you have generated before.

The line beginning with “alert” is where you can add your custom tracking code or whatever action you wish to happen when a user likes your website.

The text “en_US” means “English/US” and defines the locale setting. If you’ve got a German website you would use “de_DE” here etc.

So that’s basically all you have to do to support the button element with standard JavaScript.

Adding The Core Code With Prototype.Js

As you might know I’m using the Prototype.js JavaScript Framework whenever possible so I’ve created a small JavaScript class you can use if you’re using prototype.js on your website.

Just download this file and save it as facebook.js. You can then use this code on your website – just add it to the bottom of your page as well:

<script type="text/javascript" src="facebook.js"></script>
<script type="text/javascript">
<!--
Event.observe(window, 'load', function() {
        new facebookLikeButtonClass('YOUR_FACEBOOK_APP_ID', 'en_US', function(href, widgetObject) {
                // Do something, e.g. track the click on the "Like" button here
               alert('You just liked '+href);
        });
});
//-->
</script>

Adding The Button

Now that you’ve setup the core code you can just add the “Like” button wherever you want on your page by adding this code to the page where you want the button to appear:

<fb:like></fb:like>

Now that’s all!

You can set all of the attributes for the “Like” button on the tag as well just like you would set them on the Facebook page for the iframe code.

<fb:like href="URL" layout="standard|button_count" show-faces="true|false" width="450" action="like|recommend" colorscheme="light|dark" font="arial|lucida grande|segoe ui|tahoma|trebuchet ms|verdana"></fb:like>

You can just set the values accordingly. Just make sure you’re really closing the tag with the “</fb:like>”, this separate closing tag must be used and you cannot shorten the tag as you would usually do with the “/>” at the end.

Capturing “Dislikes”

You can’t capture if the user unlikes the site by clicking on the “Like” button again. The Facebook JavaScript API just doesn’t provide any event for this.

Click here for a working example

How To Hide Links To Avoid NoFollow PageRank Sculpting Issues

Saturday, June 6th, 2009

Just recently Google’s Matt Cutts announced a change in how Google handles NoFollow attributes in links thus making a “rel=nofollow” useless on your JavaScript-enabled onClick event handlers. The best method in this case would be to hide links on your page that you would normally have used “nofollow” on so you could only show them via JavaScript.

Instead of using “rel=nofollow” on your links as you did previously you may want to hide the links completely and only make them appear when JavaScript is enabled. You should also show a user which does not have JavaScript enabled that there is a link but it is not enabled. So I decided to create a small JavaScript which converts <span> elements with a specific class name to links when the user has JavaScript enabled. If there is no Ja

vaScript the “links” will look like this:
followlink_1

If JavaScript is enabled and the page has finished loading the links will look like this:
followlink_2

This is the HTML code for the <span> tag which will be converted into a link which needs to be given as the title attribute of the element:

1
<span class="hiddenJSLink" title="http://www.saschakimmel.com/">Hidden Link</span>

This is how the link will look after the script has been executed:

1
<a href="http://www.saschakimmel.com/">Hidden Link</a>

You can also add both an id and additional classes to the source <span> – they will be copied to the final link.

The script requires the prototype.js JavaScript framework – I am using this because I know that many websites are already using it on their pages.

This is some code of an example HTML page – you can download it and the JavaScript file in a package below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!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" xml:lang="de" lang="de">
<head>
<title>Hidden Links</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="hiddenLinks.css" type="text/css" />
<script type="text/javascript" src="prototype-1.6.0.3.js"></script>
<script type="text/javascript" src="hiddenLinks.js"></script>
</head>
<body>
<ul>
<li><a href="http://www.saschakimmel.com/">Normal Link</a></li>
<li><span class="hiddenJSLink" title="http://www.saschakimmel.com/">Hidden Link</span></li>
</ul>
</body>
</html>

So in essence the only thing you need to do is to add these three lines of code to the <head> section of your HTML file after you have downloaded the JavaScript/HTML/CSS package below:

1
2
3
<link rel="stylesheet" href="hiddenLinks.css" type="text/css" />
<script type="text/javascript" src="prototype-1.6.0.3.js"></script>
<script type="text/javascript" src="hiddenLinks.js"></script>

Acessibility Notice!

Please note that from an accessibility standpoint using JavaScript is not recommended as it renders the links useless on screen readers. But currently there seems to be no other way to hide links from Google for legitimate PageRank sculpting.

License

Creative Commons License
This code by Sascha Kimmel is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License. This means that if you are using it on your site (personal and commercial sites are ok) you need to add a link somewhere (only on one page)  as provided here:

1
HiddenLinksJS by <a href="http://www.saschakimmel.com/" target="_blank">Sascha Kimmel</a>

If you don’t want to add a link to your site you can donate any amount to my PayPal account which will entitle you to use the HiddenLinkJS on any page without any requirement for adding a link:


View hiddenLinks.js
View hiddenLinks.css
View hiddenLinks.html demo page

dlnow

Tutorial: How To Use Prototype.js On Your Site

Saturday, May 30th, 2009

prototype.js is an amazing JavaScript framework that I have been using for some years now. This tutorial shows you how to work with prototype.js and what some best practices are. It won’t go into details on every available method but it will give you a quick introduction.

I apologize for the coding style but the WordPress plugin seems to eat spaces and tabs.

Obtaining Prototype.js

You can download the latest version of the prototype library from the download page and include this on your page like this if you have saved it as prototype.js in your document root directory:

1
2
3
4
5
6
7
8
9
<html>

<head>

<script src="prototype.js" type="text/javascript"></script>

...

</html>

There are also some packaged and minimized versions of the file available because the file itself is quite large.

Using Google To Load Prototype.js

Another option is using Google to include the Prototype JavaScript Library on your page thus offloading traffic from your server to Google. You can use Google’s AJAX Libraries API for that purpose. If you want to use Google which has the benefit of distributed servers around the world therefore likely speeding up the download this is how it works:

1
2
3
4
5
6
7
8
9
10
11
12
13
<script src="http://www.google.com/jsapi"></script>

google.load("prototype", "1.6.0.3");

google.setOnLoadCallback(function() {

// What to do once the file has been loaded

....

}

</script>

Throughout this tutorial I am assuming that you are loading the library without using Google as this makes initializing your own code more complicated.

JavaScript Coding With Prototype.js

After you have included the prototype.js library it’s time to start implementing your JavaScript code. With prototype.js I have come to use classes exclusively because this allows for a object-oriented architecture of your JavaScript code and encapsulates the code.

Create a new file – for demonstration purposes in this tutorial named test.js – and save it in your document root (or in any other directory like /js, just make sure to change the path accordingly in the <script> tag). Now add the following code to it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Create the class

var myTestClass = Class.create({

initialize:function()

{

// Is called when the page has finished loading by the Event.observe code below

alert('Works!');

}

});

// Global variable for the instance of the class

var myTest;

// Creating an instance of the class if the page has finished loading

Event.observe(window, 'load', function() {

myTest = new myTestClass();

});

Now you need to create an HTML file named test.html containing the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<html>

<head>

<title>prototype.js Test</title>

<script type="text/javascript" src="prototype.js"></script>

<script type="text/javascript" src="test.js"></script>

</head>

<body>

<h1>prototype.js Test</h1>

<div id="container" style="display:none"></div>

<ul id="list">

<li>Item 1</li>

<li class="highlight">Item 2</li>

<li>Item 3</li>

<li>Item 4</li>

</ul>

<a href="http://www.dzone.com/" target="_blank" id="demoLink">Click me!</a>

</body>

</html>

If you then load this file in your browser a JavaScript alert box will pop up saying “Works”.

By creating an event hook for the window’s load event handler you can be sure that every element on the page has been loaded. If you are not using this code and leave out the Event.observe code in the test.js file it may happen that some elements on your page may not yet have loaded so the user may receive a JavaScript error message if you are trying to access elements on the page that do not yet exist.

You can also use ‘dom:loaded‘ instead on ‘load‘ in the Event.observe call which will be executed once the DOM tree of the HTML document has been fully created. This means that individual elements may not have been loaded (e.g. an image) but you can already access all of the elements on the page.

The Constructor

Whenever a new instance of a class is created the initialize() method of the class is called automatically (just like PHP’s __construct() method). You can of course define an arbitrary number of parameters as well. Just modify the line to see how it works:

1
2
3
4
5
6
7
8
9
initialize:function(url)

{

// Is called when the page has finished loading by the Event.observe code below

alert('Works @ '+url);

}

and

1
2
3
4
5
Event.observe(window, 'load', function() {

myTest = new myTestClass(location.href);

});

Methods

Defining methods within the class is very easy. In contrast to other programming languages you cannot declare specific methods (functions) as private, protected or public thus they can be accessed from the outside anyways even if you do not desire it.

Let’s create a new method and modify the class so that it looks like in this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var myTestClass = Class.create({

initialize:function(url)

{

// Is called when the page has finished loading by the Event.observe code below

alert('Works @ ' + this.toUppercase(url));

},

toUppercase:function(str)

{

return str.toUpperCase();

}

});

Please note the specific syntax for creating new methods. Every method must be separated by the one before with a comma and the last method in the class must not be followed by a comma (Internet Explorer does not like this).

You can simply call methods by prefixing them with a “this.” from within the class.

Accessing Elements

The most often used function from my experience is the $() function which allows you to access any element that has an id. The HTML code contains a link to dzone.com which has an id. To access that element you simply need to write

1
$('demoLink')

No need to write the long document.getElementById(‘demoLink’) anymore. Here is an example you can add to the initialize() method at the very end:

1
alert($('demoLink').getAttribute('href'));

This will show an alert box with http://www.dzone.com in it. Likewise you can set specific attributes easily:

1
2
3
$('demoLink').setAttribute('href', 'http://www.saschakimmel.com/');

alert($('demoLink').readAttribute('href'));

This will change the href attribute pointing to this blog’s homepage.

Now you may feel tempted to give any element that you may wish to access a specific id attribute. But wait – that’s not required! The Prototype library contains the $$() method which allows you to use CSS3 selectors (yes, even if the browser does not yet support it). So just as you might do with CSS you can do with prototype.js:

1
$$('#list li.highlight')[0].update('I was Item 2');

The $$() method always returns an array. Because our code only contains a single LI element with the given class “highlight” in an unordered list with the id “list” this code works.

You could even use something like this to achieve the same result:

1
$('list').down('li.highlight').update('I was Item 2');

The Element.up() and Element.down() methods return only a single element which is the first element found from the element given and also support CSS3 selectors.

The Element.select() method is similar to $$() but whereas the $$() method searches globally the select method searches from the given element within the DOM tree so you could also have used this code as well:

1
$$('ul')[0].select('.highlight')[0].update('I was Item 2');

This code may look a bit complex at the beginning but if you start using the library you will quickly recognize the different methods. I just urge you not to give every single element an id so that you can access it by using the $() method. You should use ids on semantic blocks like #topbar, #navigation and so on and use classes within the code wherever possible.

This way you are not blowing up your code by only using ids for accessing elements with JavaScript. It’s just not necessary if you’re using the prototype.js library.

Add more semantics to your code.

Updating And Modifying Elements And Classes

As you have already seen in the examples above you can use the Element.update() method to update element contents. If you wish to modify attributes you should use the Element.setAttribute() method (which is a native browser method).

You can also add, edit and remove class names at runtime easily.

To add a CSS class use the Element.addClassName() method:

1
$('demoLink').addClassName('democlass');

To find out whether a specific element has a specific class use Element.hasClassName():

1
2
3
4
5
6
7
$('demoLink').addClassName('democlass');

if ($('demoLink').hasClassName('democlass')) {

alert('Yikes!');

}

Loops

Forget those annoying for loops you have learned when using JavaScript. Prototype has its own methods that ease the implementation of loops. There are some pitfalls however which I am going to explain here.

We now want to loop over the <li> elements of the list and wrap a <strong> around the current contents of each <li> element. This is how it works:

1
2
3
4
5
$$('#list li').each(function(el) {

el.update('<strong>'+el.innerHTML+'</strong>');

});

In fact this is a method that is a bit dirty because we are using HTML code as a string in the update() method. This is a cleaner method but it’s very long in contrast to the method before:

1
2
3
4
5
6
7
8
9
10
11
12
13
$$('#list li').each(function(el) {

var oldContent = el.innerHTML;

var strongEl   = new Element('strong');

el.update('');

el.appendChild(strongEl);

strongEl.update(oldContent);

});

Most of the time I’m sticking with the shorter method above.

Using bind()

Now let’s call the toUppercase method we created in our class. Because the each() method has been implemented by prototype.js using the this keyword within the each loop would reference the each method itself so this will throw the error “this.toUppercase is not a function”:

1
2
3
4
5
$$('#list li').each(function(el) {

el.update('<strong>'+this.toUppercase(el.innerHTML)+'</strong>');

});

So in this case we need to bind the this keyword to our class. This can be achieved by using the bind() method:

1
2
3
4
5
$$('#list li').each(function(el) {

el.update('<strong>'+this.toUppercase(el.innerHTML)+'</strong>');

}.bind(this));

Now our code works! Whenever you are using specific prototype.js methods where you can use a this inside the method you need to bind it to your class in that way.

Event Handlers

Remember this code?

1
<a href="..." onclick="doThis()">Click here</a>

Or even this code?

1
<a href="<a href="javascript:doThis">javascript:doThis</a>()">Click here</a>

You don’t need this with prototype.js anymore as you can use the unobtrusive event handlers it provides. If a link is only useful and functional with JavaScript enabled only you should add a CSS style of “display:none” to the element and make it visible in the initialize() method.

Now let’s add an event listener to the link:

1
$('demoLink').observe('click', function() { alert('This link has been disabled!'); });

If you reload the page and click on the link you will see an alert box and if you click on the OK button the link will be opened in a new window/tab anyways. To prevent this you need to stop the event. Just modify the code to look like this:

1
$('demoLink').observe('click', function(e) { alert('This link has been disabled!'); Event.stop(e); });

As you see now the link is no longer opened. However using anonymous functions inline is not a good programming style so let’s create an additional method in our class:

1
2
3
4
5
6
7
8
9
showDisabledMessage:function(e)

{

Event.stop(e);

alert('This link has been disabled!');

},

You also need to modify the Event observer:

1
$('demoLink').observe('click', this.showDisabledMessage.bindAsEventListener(this));

Just as you did before with the call to the bind() method when using the each method when using an event listener you need to use the bindAsEventListener() method to bind the function to your class.

Here is some more code for you to see some more of what is possible with event listeners:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$('demoLink').observe('mouseover', function(e) { Event.element(e).setStyle({

'color': 'red',

'fontSize':'30px'

}); });

$('demoLink').observe('mouseout', function(e) { Event.element(e).setStyle({

'color': 'blue',

'fontSize':'12px'

}); });

I won’t go into the details on these methods so please have a look at the documentation.

AJAX

I know I have to show some demo code for AJAX usage when writing an article on the Prototype.js JavaScript framework so here we go. Create an HTML file named ajax.html and add the following code to it:

1
2
3
4
5
<div style="border:5px solid red;padding:15px;">

<h1>Loaded via AJAX!</h1>

</div>

We now want to update the <div> with the id “container” with this content after the ajax.html file has been loaded via AJAX after clicking on the link. Let’s clean up the code of the initialize() method:

1
2
3
4
5
6
7
initialize:function(url)

{

$('demoLink').observe('click', this.loadContent.bindAsEventListener(this));

},

Now add this method to the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
loadContent:function(e)

{

Event.stop(e);

new Ajax.Updater('container', 'ajax.html', {

onComplete:function() {

$('container').show();

}

});

},

This method stops the event (i.e. it won’t open the dzone.com homepage in a new window/tab), sends an AJAX request to the ajax.html file, updates the div with the id “container” (the first parameter) and when the request has finished makes the container visible with the show method as it has an inline style reading “display:none”.

As you see you don’t even need any dynamic code on the server to use AJAX.

In this article I have only scratched the surface of what prototype.js has to offer. In encourage you to read the documentation and just play around with the methods. Prototype.js has so much in store it’s really fun developing. As you may have noticed in the article I am using unobtrusive JavaScript which means that there is not a single line of JavaScript code in the HTML file (except the two <script> elements of course).

Download the source code

How To Achieve Maximum Website Performance (Part 2)

Sunday, May 10th, 2009

This is the second article in the article series on how to maximize your website performance. I assume that you have also read the previous article which defines the basics of performance optimization.

After optimizing the time to the first byte received the next step is to decrease the load time of your website.

3. Decreasing Load Time

The less bytes are to be transferred the better. But you may also want to check your webhost first because if the connection to your server is very slow that might be the root of the problem – not necessarily the number of bytes to be transferred.

Checking Your Server Performance

To check this you should upload a large file to your server – maybe 10 megabytes at the very least – the larger the better. You should also ensure that your own internet connection does not suffer from any problems while you are testing. All downloads and other programs (like email clients) should be shutdown prior to testing.

Please note that this test only shows the maximum speed of both your server and your own internet connection combined. If your server is connected to the network with 100 Mbps but your internet connection is just 1 Mbps you will only be able to measure 1 Mbps as the maximum speed so depending on your connections it may not make sense to measure the speed.

Now you need to have a stopwatch ready as you need to measure the time from starting the download to the download being finished. Let’s say the file you have uploaded has a size of 2 MB. You now have to divide the file size by the number of seconds it took to download. If it took 10 seconds to download the file the connection speed is something like 2MB/10 seconds = 0.2 Mbps = 200k/s.

You may also use DownTester (freeware) to measure the download speed automatically.

To measure the performance of your internet connection I recommend using SpeedTest.

If you have found out that the server speed is indeed very low compared with what you would expect check back with your webhost.

Image Optimization

Now it’s time to review the images on your page. Select “Images” > “View Image Information” in your Web Developer Toolbar after you have opened your website again in your Firefox browser.

webdeveloper

This will open a new tab which will list all of the images on your website including information on image dimensions, URL and file size. Have a careful look at the number of total image requests – the higher the more you can optimize.

webdeveloper-image-count

While scrolling down always have a look at the file size for each image. There is not a rule of thumb regarding the file size of an image because it depends on the file type of the image and the dimensions.

Image Types – What’s Right And What’s Wrong

I am still amazed when I see how many web developers still do not know which image file formats to use for different kinds of images. There are only three main types of images used on the web (yes, I won’t talk about SVG and other formats here) and supported by all major browsers:

  • GIF
    The GIF format should never ever be used to compress photos because it has been developed for images with a maximum of 256 colors and works best with images that contains a small number of colors and especially large chunks of pixels with the same color.
    This is the optimal format for screenshots of an application and for graphics with a small number of different colors.
    When compressing GIF images you can choose the maximum number of colors. Sometimes just 16 colors or even just two may be enough however in my opinion you should not invest hours to optimize images just to gain a total 10 KB out of it.
    Supports one color to be used as a transparent color. Supports animations as well.
  • JPEG
    The JPEG format (the “P” actually stands for “photographic”) has been developed for true-color images, mostly for photos. It should never be used for screenshots beause it uses far more storage capacity (and therefore load time) than required.
    No support for a transparent color, no support for animations.
  • PNG
    Nowadays PNG files – although originally developed to be used online – are seldom used for normal images on a website. From my experience it does not make sense to use PNG graphics most of the time except you want to use the so-called alpha transparency feature which in contrast to the GIF transparency offers a full 256 bits channel for transparency. This means that you cannot only pick one single color that is transparent but several grey scale values which are semi-transparent. This allows for seamless integration onto any background.
    Most of the time I am only using PNG images if I need alpha transparency.
    There are currently two formats implementing animations for PNG.

Sample Images – Learning By Seeing

Just have a look at the following images to see the differences in image types and compression. You should see very clearly when not to use JPEGs and prefer GIF images instead.

Photo (bad, saved as GIF, 32K)

Photo (bad, saved as GIF, 32K)

Photo (good, saved as JPEG, 21K)

Photo (good, saved as JPEG, 21K)


Screenshot (good, saved as GIF, 5K)

Screenshot (good, saved as GIF, 5K)

Screenshot (bad, saved as JPEG, 15K)

Screenshot (bad, saved as JPEG, 15K)


Screenshot (good, saved as GIF, 5K)

Screenshot (good, saved as GIF, 5K)

Screenshot (bad, saved as JPEG, 8K)

Screenshot (bad, saved as JPEG (90%), 8K)


Screenshot (good, saved as GIF (8 colors), 2K)

Screenshot (good, saved as GIF (8 colors), 2K)

Screenshot (bad, saved as JPEG (20%), 3K)

Screenshot (bad, saved as JPEG (20%), 3K, still larger than the GIF)


Screenshot (good, saves as PNG (truecolor), 4K)

Screenshot (good, saves as PNG (truecolor), 4K)



You should have seen that GIF offers good quality and still requires less bytes for certain images.

After you have optimized your images (Corel PhotoImpact offers a very cool image optimization assistant for JPEG, GIF and PNG) now it’s time to look at your CSS and JS code on the page.

Optimizing CSS and JS code

Are you using Cascading Style Sheets (CSS) and JavaScript on your page? For this optimization it does not matter whether the code is embedded on your website or has been outsourced to an external file. Just look at your CSS and JavaScript code and remove unnecessary comments first.

Now it’s time to compress your CSS and JavaScript files. There are free online services available to compress CSS and JS code. I recommend using CSSDrive to compress your CSS code and JavaScriptCompressor.com to compress your JavaScript code.

You should save the compressed code to another file than your original file otherwise you won’t be able to edit the code later on unless you are a bot of course.
Just remember that you have to repeat this process every time you modify your CSS or JS code. In a later article I will show how you can automate this process completely with PHP.

Cleaning Up The HTML Code

Now have a closer look at your HTML code. Are there large chunks of code in comments? Remove the comments that are no longer useful.

Embedded Code From External Domains

Is there any popular website that doesn’t offer embeddable content? Yes, embeddable content can be quite cool but it may also slow down the loading time of your page especially if the code snippet you have inserted into your page uses JavaScript because your browser will stop rendering the page right where the JavaScript code has been embedded until it has been executed successfully. If an external source is unavailable or very slow your page will get stuck while loading.

I even had to remove some ad server code some months ago from one of my pages because the ad server was so slow that even after one minute my page was still showing just half of the page rendered. This is not an impressive or professional view. It makes you look like an amateur.

To find out which sources are slow you only have to look at the status bar of your browser to see what is currently happening. “Waiting for ….” is an indication.

Sometimes I also experience slower load times on my page because of the Google Friend Connect Widget embedded on the sidebar to the right. You should check the code one-by-one and decide if you really need this specific widget, snippet or feature.

There are many sites that allow you to embed buttons on your own website to link to your Twitter, Facebook, LinkedIn, MySpace etc. profile and just give you a JavaScript snippet to put onto your site. You should think about using static images to upload onto your server and link to the pages manually.

This concludes the second part of the article series. The next part will focus on how to minimize the number of requests on your page. Some of the optimizations discussed in this article will be revisited to further improve the performance of your website. Click to read the next part now.

tweetthis-15

How To Create A Dynamic “Tweet This” Button With JavaScript

Wednesday, May 6th, 2009

Yesterday I posted some code on how to create dynamic Tweet This buttons with PHP, today I’m going to share a short code snippet you can really drag and drop into your editor to create a “Tweet This” button on your website.

You just need to copy and paste this code and adjust the src attribute of the image to point to your button:

1
2
3
4
5
6
7
8
9
10
<script type="text/javascript">
var twtTitle  = document.title;
var twtUrl    = location.href;
var maxLength = 140 - (twtUrl.length + 1);
if (twtTitle.length > maxLength) {
twtTitle = twtTitle.substr(0, (maxLength - 3))+'...';
}
var twtLink = 'http://twitter.com/home?status='+encodeURIComponent(twtTitle + ' ' + twtUrl);
document.write('<a href="'+twtLink+'" target="_blank"'+'><img src="tweetthis.gif"  border="0" alt="Tweet This!" /'+'><'+'/a>');
</script>

tweetthis-15