Wednesday, 13 July 2011

PHP for obtaining the follower count of a Twitter Account

Get Twitter Follower Count using Regular Expressions

I came across this bit of PHP code the other day which is aimed at getting the follower count of a Twitter user.

It seems like overkill to me and is a mixture of regular expressions, string parsing, callback functions and a lot of head scratching.

The user obviously knows that the follower count HAS to reside within an element within the DOM with the id of follower_count so why not just use one single regular expression to target that element and return it's guts instead of all the DOM loading, callbacks and string parsing?

I might be missing something that someone could tell me but this seemed like a long way to go about a simple scrape job.


// Get the number of twitter followers

function string_getInsertedString($long_string,$short_string,$is_html=false){
if($short_string>=strlen($long_string))return false;
$insertion_length=strlen($long_string)-strlen($short_string);
for($i=0;$i<strlen($short_string);++$i){
if($long_string[$i]!=$short_string[$i])break;
}
$inserted_string=substr($long_string,$i,$insertion_length);
if($is_html && $inserted_string[$insertion_length-1]=='<'){
$inserted_string='<'.substr($inserted_string,0,$insertion_length-1);
}
return $inserted_string;
}

function DOMElement_getOuterHTML($document,$element){
$html=$document->saveHTML();
$element->parentNode->removeChild($element);
$html2=$document->saveHTML();
return string_getInsertedString($html,$html2,true);
}

function getFollowers($username){
$x = file_get_contents("http://twitter.com/".$username);
$doc = new DomDocument;
@$doc->loadHTML($x);
$ele = $doc->getElementById('follower_count');
$innerHTML=preg_replace('/^<[^>]*>(.*)<[^>]*>$/',"\\1",DOMElement_getOuterHTML($doc,$ele));
return $innerHTML;
}


// To display it

<?php echo getFollowers("username"); ?>



Here is the much shorter version I wrote. It still works just as well returning the follower count of the Twitter Account username passed into it.

function getFollowers($username){
$url = "http://twitter.com/".$username;
$count=0;

$x = file_get_contents($url);

preg_match("@<([a-z][^ ]*) id=\"follower_count\"[^>]+?>([0-9,]+)\s*</\\1>@i",$x,$match);

if($match){
$count = $match[2];
}

return $count;
}

// lets check how poorly my twitter account is followed!
echo "StrictlyTweets: " . getFollowers("StrictlyTweets") . "<br><br>";



As you can see from the regular expression I am matching HTML tags (they all start with < and then a letter) and storing that tag to be used in the backtrack reference later on so that if the HTML changes from a SPAN to a DIV as long as it has the id="follower_count" with the element there will be a match.

I could have loaded up the DOM, targeted the ID and then done some regex but why bother when you can go straight for the juggular!

Tuesday, 12 July 2011

Firefox 5.0 Firebug 1.8 Memory Leak Problem

Firefox 5.00 with Firebug 1.8.0b5 on Windows 7 64 bit causes Memory Leak

I came across a problem with Firefox 5.0 and Firebug 1.8.0b5 today that basically leaked memory like an open oil well and hung my PC every time I tried to open up a basic popup window from a page using Javascript.

My PC is running the following:

Windows 7 - Dual Core - 64 Bit
Firefox.exe *32 - version 5.0
Firebug 1.8.0b5

This problem has only started occurring since my latest upgrade and I narrowed it down to Firebug by disabling each plugin one by one.

I can replicate the problem on one particular page quite easily which has a link with a simple javascript: window.open(url) function that opens up a little static html page.

When I now click the link the popup opens full size rather than the dimensions set 400px * 400px and there is nothing on the page - just a blank screen. Viewing the source shows nothing at all.

This page used to work fine before the update.

It still works on all other browsers Chrome, Safari, IE (6 to 9) and it still works in Firefox 5.0 on 32 bit machines so I am not sure whether it's a 64 bit problem or not.

Viewing my Task Manager window I can open Firefox and I can get my Firefox to use beyond 1GB of memory and 50% CPU (the whole of one of my two processors) with only one single window and tab open all within 5 minutes.

Earlier today it was using over 3GB of memory!

Another clue is the fact that the error console is permanently full of these error messages:

attempt to run compile-and-go on a cleared scope
resource://firebug_rjs/console/errors.js
line 156

Hitting clear just fills up the whole of Firebug's console log instantly with the same message.

The only way I have found to solve this problem is to disable Firebug and not use the "Restart Firefox" link as this seems to just ramp the memory up without shutting the process down first.

I usually have to kill the process through Task Manager as clicking the close button doesn't do anything the majority of the time.

If anyone else has similar problems please let me know.


Saturday, 9 July 2011

URLEncode Problem with .NET 4.0

Visual Studio 2010 Problem with "The name HttpUtility does not exist in the current context".

I usually use Visual Studio 2010 at work and the Express edition at home. Tonight I was knocking up quick C# windows form application to crawl some specific URL's and I required the ability to URL Encode my URI Components e.g

string url = "http//somesite.com/search?qry=" +  System.Web.HttpUtility.UrlEncode(val);

However even though I had included:

using System.Web;

At the top of my class it was saying that HttpUtility could not be found in System.Web.

This was driving me crazy as I had another project open at the same time which was using the exact same code and it worked.

The advice I found on the web said to ensure that a reference to System.Web was added with the "Project" > "Add References" option.

However when I was searching for this DLL all I could find were System.WebServices and System.ApplicationServices which were obviously no good.

However after a lot of head scratching I went back to the main Project Properties panel and under Target Framework I had ".NET Framework 4 Client Profile" Selected.

I changed this first to .NET Framework 3.5 and then looked again for the reference and it worked!

I added it and then changed it back again to .NET Framework 4. On re-opening the project  all my problems had been solved.

Don't ask me why System.Web doesn't appear as a reference under the Client versions but it doesn't and you need to add a proper DLL reference to get to use this sort of functionality if you are doing non web based apps that require web based functionality like URL or HTML Encode etc.

I thought I would just write a few notes about this in-case anyone else experiences the same problem.

Tuesday, 5 July 2011

TSQL UDF to return useful dates

A User Defined Function to return useful dates

I had to come up with some calculations for working out the starting and end weekday for a given date earlier and I wrote this UDF for SQL 2000, 2005, 2008.

It returns a number of useful values including dates and strings (which is why the return value is a varchar).

If you want to know the last working day for the current month, last month or the last weekday for a month then this function will help.

You can pass in the current date e.g GETDATE() or pass in your own datetime value.


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

=============================================================================
-- Author: Rob Reid
-- Create date: 05-JUL-2011
-- Description: Returns useful dates for calculations and formatting
/*


-- example usage

DECLARE @dte datetime
SELECT @dte = GETDATE() --OR pass in a literal date e.g '2011-Jun-03 03:54:00'

SELECT dbo.udf_GET_DATE_OF('FIRST DAY OF LAST MONTH',@dte) as 'First Day of Last Month',
dbo.udf_GET_DATE_OF('FIRST DAY OF MONTH',@dte) as 'First Day of Month',
dbo.udf_GET_DATE_OF('LAST DAY OF MONTH',@dte) as 'Last Day of Month',
dbo.udf_GET_DATE_OF('LAST DAY OF WEEK',@dte) as 'Last Day of Week',
dbo.udf_GET_DATE_OF('FIRST DAY OF MONTH',@dte) as 'First Day of Week',
dbo.udf_GET_DATE_OF('LAST WORKING DAY OF MONTH',@dte) as 'Last Working Day of Month',
dbo.udf_GET_DATE_OF('LAST WORKING DAY OF LAST MONTH',@dte) as 'Last Working Day of Last Month',
dbo.udf_GET_DATE_OF('FIRST WEEKDAY OF MONTH',@dte) as 'First Week Day of Month',
dbo.udf_GET_DATE_OF('LAST WEEKDAY OF MONTH',@dte) as 'Last Week Day of Month'



*/
=============================================================================


CREATE FUNCTION [dbo].[udf_GET_DATE_OF]
(
@rule varchar(30),
@dte datetime
)
RETURNS VARCHAR(30) AS
BEGIN

DECLARE @ret varchar(30)

IF @rule = 'FIRST DAY OF LAST MONTH'
BEGIN
SELECT @ret = '01/' + UPPER(LEFT(DATENAME(MONTH,DATEADD(MONTH,-1,@dte)),3)) + '/' + CAST(YEAR( DATEADD(MONTH,-1,@dte) ) as varchar(4))
END
ELSE IF @rule = 'FIRST DAY OF WEEK'
BEGIN
SELECT @ret = DATEADD(dd,-(DATEPART(dw, @dte) - 1),@dte)
END
ELSE IF @rule = 'LAST DAY OF WEEK'
BEGIN
SELECT @ret = DATEADD(dd,-(DATEPART(dw, @dte) - 7),@dte)
END
ELSE IF @rule = 'FIRST DAY OF MONTH'
BEGIN
SELECT @ret = DATEADD(dd,-(DAY(@dte)-1),@dte)
END
ELSE IF @rule = 'LAST DAY OF MONTH'
BEGIN
SELECT @ret = DATEADD(d, -DAY(DATEADD(m,1,@dte)),DATEADD(m,1,@dte))
END
ELSE IF @rule = 'FIRST WEEKDAY OF MONTH'
BEGIN
SELECT @ret = DATENAME(dw, DATEADD(dd, - DATEPART(dd, @dte) + 1, @dte))
END
ELSE IF @rule = 'LAST WEEKDAY OF MONTH'
BEGIN
SELECT @dte = DATEADD(dd,-(DAY(@dte)-1),DATEADD(MONTH,1,@dte)),
@ret = DATENAME(dw,CONVERT(VARCHAR, DATEADD(DAY, 0 - ((DATEPART(DAY, @dte)) +
CASE WHEN DATENAME(WEEKDAY, DATEADD(DAY, 0 - (DATEPART(DAY, @dte)), @dte)) = 'SUNDAY' THEN 2
WHEN DATENAME(WEEKDAY, DATEADD(DAY, 0 - (DATEPART(DAY, @dte)), @dte)) = 'SATURDAY' THEN 1
ELSE 0 END
), @dte), 113))

END
ELSE IF @rule = 'LAST WORKING DAY OF LAST MONTH'
BEGIN
SELECT @ret = CONVERT(VARCHAR, DATEADD(DAY, 0 - ((DATEPART(DAY, @dte)) +
CASE WHEN DATENAME(WEEKDAY, DATEADD(DAY, 0 - (DATEPART(DAY, @dte)), @dte)) = 'SUNDAY' THEN 2
WHEN DATENAME(WEEKDAY, DATEADD(DAY, 0 - (DATEPART(DAY, @dte)), @dte)) = 'SATURDAY' THEN 1
ELSE 0 END
), @dte), 113)
END
ELSE IF @rule = 'LAST WORKING DAY OF MONTH'
BEGIN
SELECT @dte = DATEADD(dd,-(DAY(@dte)-1),DATEADD(MONTH,1,@dte)),
@ret = CONVERT(VARCHAR, DATEADD(DAY, 0 - ((DATEPART(DAY, @dte)) +
CASE WHEN DATENAME(WEEKDAY, DATEADD(DAY, 0 - (DATEPART(DAY, @dte)), @dte)) = 'SUNDAY' THEN 2
WHEN DATENAME(WEEKDAY, DATEADD(DAY, 0 - (DATEPART(DAY, @dte)), @dte)) = 'SATURDAY' THEN 1
ELSE 0 END
), @dte), 113)
END

RETURN @ret


END


The example usage is given in the UDF definition e.g

DECLARE @dte datetime
SELECT @dte = GETDATE() --OR pass in a literal date e.g '2011-Jun-03 03:54:00'

SELECT dbo.udf_GET_DATE_OF('FIRST DAY OF LAST MONTH',@dte) as 'First Day of Last Month',
dbo.udf_GET_DATE_OF('FIRST DAY OF MONTH',@dte) as 'First Day of Month',
dbo.udf_GET_DATE_OF('LAST DAY OF MONTH',@dte) as 'Last Day of Month',
dbo.udf_GET_DATE_OF('LAST DAY OF WEEK',@dte) as 'Last Day of Week',
dbo.udf_GET_DATE_OF('FIRST DAY OF MONTH',@dte) as 'First Day of Week',
dbo.udf_GET_DATE_OF('LAST WORKING DAY OF MONTH',@dte) as 'Last Working Day of Month',
dbo.udf_GET_DATE_OF('LAST WORKING DAY OF LAST MONTH',@dte) as 'Last Working Day of Last Month',
dbo.udf_GET_DATE_OF('FIRST WEEKDAY OF MONTH',@dte) as 'First Week Day of Month',
dbo.udf_GET_DATE_OF('LAST WEEKDAY OF MONTH',@dte) as 'Last Week Day of Month'



I have found this very useful lately when calculating certain statistical reports and maybe some of you will as well.

Thursday, 30 June 2011

Please do not ask me to earn your wages for you

Another rant about Open Source development

I would like all my readers and especially the tens of thousands of people who have downloaded my Wordpress Plugins to please remember the following >> I am currently giving my plugins away for free and relying on Google adsense clicks and donations to help fund my development time.

So far I have had a few £60 payments from Google and a minimal amount of donations. I have welcomed every donation so far so please don't think they are not appreciated but when you usually work for £700 a day having a donation for £1 or £2 once a fortnight which relates to about 3,000 downloads is a bit disheartening.

I know I have blogged about how much I hate open source coding before but I am honestly of the opinion that a number of UK and US companies are outsourcing high quality IT developer jobs to India (because it seems you can find a developer willing to write whole websites for less than a £50 somewhere on that sub-continent) only for those same developers to fill up my inbox or comment sections with requests for me to do their work for them for free.

In fact probability suggests that I have more than likely ended up doing some Indians work for them for free who stole the original contract from myself due to undercutting my reasonable and realistic quote for a £10!

It would be quite funny if not so sad and unfortunate but it seems that too many IT managers and company directors have no idea about the value of a qualified and experienced IT developer nowadays and it's only through their incessant cost cutting that they will learn the hard way.

It is also for this reason that I am going to refuse to do any custom development for any of my plugins unless partial payment is received up front.

On numerous occasions, and sadly this even includes multi-national companies, I have had people contact me and promise reasonable sized donations for specific features to be developed only for them to swerve me once the work has been done.

Due to the GPL nature of Wordpress there is little scope for money making unless you do most of your work with remote procedure calls or mask your code some way which unlike C# and .NET is pretty hard with PHP as you cannot easily convert your code to a compiled DLL or equivalent compiled file type.

Therefore if you have any requirements or ideas for improvements to my plugins you may email me with your request but please don't expect a reply unless you are willing to pay for the work up front. I am a reasonable man and will accept half up front and half on completion but I have lost faith in mankind to keep their word and there are way too many shysters for my liking.

Either steal my code without me knowing about it or pay me for it.

DO NOT ask to steal my code it makes no fucking sense at all! (this has actually happened)

If you cannot code and are incapable of amending or making your own plugins like I had to do or you are too stupid to steal code without being caught then be a real man and ask the developer what price they will accept.

Do not promise them a tenner for a grands worth of work and do not get annoyed when you ask if your specific feature is something I am thinking of introducing in a future release and I reply "not unless someone pays me to do it".

I have long passed the time in my life where I code other peoples work for fun just so that they can earn money off my hard labour.

My rant is officially over. Thank you for listening.

Why is Strictly AutoTags a good tagging plugin

Strictly AutoTags - Is it a good plugin?

As the author of the top rated Strictly AutoTags Wordpress plugin that at the time of writing has been downloaded over 35,000 times and still has 5 stars I am bound to be biased towards it.

You can read all about my plugin on my main website or view many of the reviews people have written about it on-line however I thought I would quickly list a couple of the main points which are often overlooked.

The main point is that Strictly AutoTags does not use remotely hosted API's to determine which tags to use.

Many of the other automatic tagging plugins use API's to retrieve a list of tags for their article posts. This involves sending the article to a remote site through an HTTP request and retrieving a list of tags in an HTTP response. The downsides of this approach are:
  • You are relying on a remote website and a working API for the tagging to work. If their server is down or their code is broken you will get no tags back.
  • You are relying on a 3rd party to keep a list of tags up to date. When new tags come out you must wait until they are added before they can be used. For example if a news story breaks that mentions for the first time the name of a major character within the story - say a baby goes missing or a banker commits suicide then their names are unlikely to be in any 3rd party list of tags until someone a) decides the name is worth going on the list and b) the list is updated to have the name on it.
  • You are using up bandwidth passing content back and forth from your websites server to the API server. Depending on the size of the article and the number of articles you are tagging this may or may not cost you a lot of money depending on your hosting package.
Why is the Strictly AutoTags plugin different?

Well for one it has the best of both worlds in that it uses your existing tag list to work out what words to use for post tags and therefore you can tailor your own tag list to words relevant to your sites content only and start off with as big or as small a list as possible.

Instead of using up bandwidth and relying on the 3rd party API to always be active and fast you can create your own tag list and do the same thing internally. It may not have the same size or depth of tags but you are not using bandwidth or spending time making HTTP requests to check for tags you might already have.

Another great feature is that it has an auto discovery feature which when enabled will automatically scan the content of your article for words or sentences that can be used as new tags. This is great for sites with no initial tag list as it will help build a list from scratch and it is also great for identifying the names of people who have suddenly become famous over night and are appearing in news stories before 3rd party API's have been updated.

Using my own proprietary code I scan content for possible new tags that match important English words such as names of people, companies, government office branches, football clubs and anything else that could be deemed important. This is all done without requiring the upkeep of a list of possible tags which 3rd party API's mainly rely on.

If a news story breaks about a fireman called Mike Johnson saving a baby named Amanda Jean Jones then these names would be identified as possible tags and if saved they are then available in future searches. API's relying on lists would need to add these names into their database so that users of their API could make use of them before they get tagged.

Another reason my plugin is pretty cool is that unlike some plugins that just match existing tags inside the content and then re-use them for that article my plugin checks to see how often the tags are used so only the most relevant and frequently referenced tags are added.

It also ranks each tag match depending on where it appears so that the tag "CIA" appearing in the article title or a H1 tag is ranked a lot higher than if the word just appeared in a paragraph inside the main content.

My plugin all ranks matches within all important kinds of HTML such as H1 to H6, Strong, EM, Bold, Italic and Anchor tags. A word within an H2 is ranked higher than one within an H6 or a Strong tag. These rankings are then used to order the tags so only the tags ranked with the highest score are used.

The admin user can configure the maximum number of tags that can be added per article as well as a number of other cool featured including the great for SEO option of wrapping tagged words in <STRONG>tags</STRONG> so they are considered more important than other pieces of text.

As well as being able to set up the plugin to ignore certain words or phrases as either case sensitive or case insensitive the plugin has a number of other options and I am constantly coming up with new ideas for it.

In fact I am working on a new SEO related plugin that is so black hat that I am having trouble coming up with a descriptive word for it that conveys it's total awesomeness.

If anyone has any ideas of what they would like to see in any Search Engine Optimisation plugins then please leave a comment or send me an email as the more ideas the better.

Anyway if you are currently debating on what kind of autoblogging tools to use for your Wordpress site then I suggest checking out my plugins Strictly AutoTags and Strictly Tweetbot two plugins that can save you huge amounts of time and give your blog or site an active online social media presence without lifting a finger.

Also if you are one of the 35,000 plus users of my Strictly AutoTags plugin and you have found it useful in generating you a nice a tag list or helped in driving traffic to your site then please consider donating a small amount of money to my site.

Remember that at the moment all my Wordpress Plugins are free and they take a lot of time to keep maintained as well as developing new features. Without your support I will have to stop my open source development and move back towards paid for applications which is only going to hurt current users so please consider helping me out. Remember any amount is appreciated!






Saturday, 25 June 2011

Loading Social Media Code Asynchronously

Preventing Slow Page Loads By Loading Widgets Asynchronously

I have noticed on a number of sites that use such as the popular Add This widget that for some reason many people using this code have caused problems for themselves by adding the <SCRIPT> tag that loads the widget in every place that they want the widget to display.

On a news blog with 10 articles this means that the same <SCRIPT> could be referenced 10 times. Now I know browsers are clever enough to know what they have loaded and utilise caching but as every user of Google Adsense knows having to embed <SCRIPT> tags in the DOM at the place where you want the advert to display instead of just referencing it once at the bottom of the HTML or loading it in with Javascript can cause slow page loads as the browser will hang when it comes across a script until the content has been loaded.

I have personally spent ages trying to hack Google AdSenses code about to utilise the same asynchronous loading that they now use for their Analytics code but to no avail. There code loads in multiple iframes and any hacking seems to trigger a flag their end that probably signifies to them some kind of fraudulent abuse.

However for other kinds of widgets including the AddThis widget there is no need to reference the script multiple times and I am busy updating some of my sites to utilise another method which can be seen on the following test page >> http://www.strictly-software.com/AddThis_test.htm


Loading addthis.com social media widgets asynchronously

I wanted to keep the example as simple as possible so in that regards if you use IE it's best off to view it in IE 9 as the only cross browser code I have added is a very basic addEvent function and an override for document.getElementsByClassName which doesn't exist pre IE 9.

Other browsers should work without a problem i.e Chrome, FireFox, Safari, Opera and any other standard compliant browser that supports the DOM 2 Event Model.


Specifying where the Social Media widgets will appear

HTML 5 makes use of custom attributes that validate correctly as long as they are prefixed by the name data- therefore I have utilised this much needed feature to specify the URL and the Title of the item that is to be bookmarked on the desired Social Media site.

You might have a page with multiple items, blog articles or stories each with their own Social Media widget and instead of defaulting to the URL and Title of the current document it is best to specify the details of the article the Add This widget refers to.

The HTML code for outputting a widget is below:


<div class="addthis_wrapper" data-url="http://www.strictly-software.com/twitter-translator" data-title="Twitter Translator Tool" >


Notice how the URL and Title are referenced by the

data-url="http://www.strictly-software.com/twitter-translator" data-title="Twitter Translator Tool"

attributes. You can read more about using custom HTML5 attributes as they are becoming more and more commonly used.
Changing the placeholders into Social Media widgets

Once the placeholder HTML elements are inserted into your DOM where you want the addthis widget to appear instead of doing what many Wordpress plugins and coders do and adding a reference to the hosted script next to each DIV you just need to add the following code in the footer of your file.

You can either wrap the code in an on DOM load event or an on Window load or just as I have done wrap it in a self calling function which means it will run as soon as the Browser gets to it.

You can view the code is more detail on my test page but to keep things simple I have just done enough cross browser tweaks to make it run in most browsers including older IE. There might be some issues with the actual addthis code that is loaded in from their own site but I cannot do anything about their dodgy code!

The Javascript code to change the DIV's into Social Media Widgets

(function(){
// this wont be supported in older browsers such as IE 8 or less
var els=document.getElementsByClassName('addthis_wrapper');

if(els && els.length >0){

// create a script tag and insert it into the DOM in the HEAD
var at=document.createElement('script');at.type='text/javascript';

// make sure it loads asynchronously so it doesn't block the DOM loading
at.async=true;
at.src=('https:'==document.location.protocol?'https://':'http://')+'s7.addthis.com/js/250/addthis_widget.js?pub=xa-4a42081245d3f3f5';

// find the first <SCRIPT> element and add it before
var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(at,s);

// loop through all elements with the class=addthis_container
for(var x=0;x<els.length;x++){

// store pointer
var el = els[x];

// get our custom attribute values for the URL to bookmark and the title that describes it defaulting to the placeholders that
// will take the values from the page otherwise. By using data-title and data-url we are HTML 5 compliant
var title = els[x].getAttribute("data-title") || "[TITLE]";
var url = els[x].getAttribute("data-url") || "[URL]";

// create an A tag
var a=document.createElement('A');
a.setAttribute('href','http://www.addthis.com/bookmark.php');

// create an IMG tag
var i=document.createElement('IMG');
i.setAttribute('src','http://s7.addthis.com/static/btn/lg-share-en.gif');

// set up your desired image sizes
i.setAttribute('width','125');
i.setAttribute('height','16');
i.setAttribute('alt','Bookmark and Share');
i.style.cssText = 'border:0px;';

// append the image to the A tag
a.appendChild(i);

// append the A tag (and image) to the DIV with the class=addthis_container
el.appendChild(a);

// using DOM 2 event model to add events to our element - remember if you want to support IE before version 9 you will need to either use a wrapper addEvent
// function that uses addEvent for IE (and Opera) and addEventListener for IE 9, Firefox, Opera, Webkit and any other proper broweser
addEvent(a,"mouseover",function(e){if(!addthis_open(this, '', url, title)){StopEvent(e,a)}});
addEvent(a,"mouseout",function(){addthis_close});
addEvent(a,"click",function(e){if(!addthis_sendto()){StopEvent(e,a)}});

// cleanup
el=a=i=title=url=null;
}
}
})();


The code is pretty simple and makes use of modern browsers support for document.getElementsByClassName to find all elements with the class we identified our social media containers with. This can obviously be replaced with a selector engine such as Sizzle if required.

First off the code builds a SCRIPT element and inserts it into the DOM in the HEAD section of the page. The important thing to note here is that as this code is at the bottom of the page nothing should block the page from loading and even if the SCRIPT block was high up in the DOM the code only runs once the DOM has loaded anyway.
// create a script tag and insert it into the DOM in the HEAD
var at=document.createElement('script');at.type='text/javascript';

// make sure it loads asysnchronously so it doesn't block the DOM loading
at.async=true;
at.src=('https:'==document.location.protocol?'https://':'http://')+'s7.addthis.com/js/250/addthis_widget.js?pub=xa-4a42081245d3f3f5';

// find the first <SCRIPT> element and add it before
var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(at,s);




The code then loops through each node that matches creating an A (anchor) tag and an IMG (image) tag with the correct dimensions and attributes for the title and URL. If none are supplied then the system will default to the document.location.href and document.title if no values are supplied which might be fine if it's the only widget on the page but if not values should be specified.


Events are then added to the A (anchor) tag to fire the popup of the AddThis DIV and to close it again and I have used a basic addEvent wrapper function to do this along with a StopEvent function to prevent event propagation and these are just basic cross browser functions to handle old cruddy browsers that no-one in their right mind should be using any more. As this is just an example I am not too bothered if this code fails in IE 4 or Netscape as its just an example of changing what is often plugin generated code.


You can see an example of the code here >>

http://www.strictly-software.com/addthis_test.htm

This methodology is being used more and more by developers but there are still many plugins available for Wordpress and Joomla that insert remote loading SCRIPTs all throughout the DOM as well as using document.write to insert remote SCRIPTS. These methods should be avoided if at all possible especially if you find that your pages hang when loading and as you can see from the example code it is pretty simple to convert to your favourite framework if required.