Monday, December 28, 2009

Embedding HTML from jQuery AJAX Call Into Your Page

I got an interesting Twitter question the other day and thought I would blog about it to help anyone who has a similar situation.

Question

Hey buddy! How can I do a simple thing as loading a page into a div using Ajax and on the loaded page, execute a simple task as executing a javascript with an alert box?!? The page is loaded but the javascript just doesn't run! If I access the page direct directly, the alert pops out ok! --@montedesucata

 

Scenario 1

My initial thoughts were that he was trying to put an entire HTML document (pulled back from an AJAX call) inside another HTML document (the document that made the AJAX call). You can't do that because then you’d have two html elements, two head elements, two body elements, etc... in one document. So, my first example was to put the contents into an iFrame.

Note: You can also, strip out the body content of the returned full HTML document and inject that into your current document, but then you might not have the correct scripts or css files that were included in the head element (or wherever you put those).

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Load Full HTML Document via AJAX into iFrame</title>
   <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
   <style>
      .dynamicIframe { 
         display: none; width: 100%; border: none 1px black; 
      }
   </style>   
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
   <script type="text/javascript">
   $(function() {
      $('#load').click(function() {
         $.ajax({
            type: "GET",
            url: "FullTestHtmlWithAlert.html", 
            dataType: "html",
            success: function(html) {
               $("#dynamicContent")
                  .contents().find("body")
                  .html(html).end().end()
                  .fadeIn('slow');               
            }
         });
         return false;
      });
   });
   </script>   
</head>
<body>
   <h3>Load Full HTML Document via AJAX into iFrame</h3>
   <button id="load">Load</button><br/>
   <iframe id="dynamicContent" class="dynamicIframe"></iframe><br/>
</body>
</html>

The contents of the FullTestHtmlWithAlert.html are below…

<!-- FullTestPageWithAlert.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Load Full HTML Document via AJAX into iFrame</title>
   <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
   <script type="text/javascript">
      alert('Hello World!');
   </script>
</head>
<body>
   <h3>Hello World From Full Html Document</h3>
</body>
</html>

The following is a screenshot of the results after clicking the Load button.

LoadFullHtmlDocumentViaAjaxIntoIframe

Feel free to Demo the above code below...

cooltext439924698

Scenario 2

The other scenario is that the HTML from the AJAX call is a partial document, meaning that it doesn’t include html, head, body, etc… tags and is just content that might be found in a body tag. This is a simpler case and the results can easily be injected into another DOM element in the document.

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Load Full HTML Document via AJAX into iFrame</title>
   <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
   <script type="text/javascript">
   $(function() {
      $('#load').click(function() {
         $.ajax({
            type: "GET",
            url: "PartialTestHtmlWithAlert.html", 
            dataType: "html",
            success: function(html) {
               $('#dynamicContent').html(html)
                  .fadeIn('slow');
            }
         });
         return false;
      });      
   });
   </script>   
</head>
<body>
   <h3>Load Parital HTML Document via AJAX into Div</h3>
   <button id="load">Load</button><br/>
   <div id="dynamicContent" style="display: none;"></div>
</body>
</html>

The contents of the PartialTestHtmlWithAlert.html are below…

<!-- PartialTestPageWithAlert.html -->
<script type="text/javascript">
alert('Hello World!');
</script>
<table>
    <tr>
        <td>1</td>
        <td>2</td>
    </tr>
    <tr>
        <td>a</td>
        <td>b</td>
    </tr>
</table>

The following is a screenshot of the results after clicking the Load button.

LoadPartialHtmlDocumentViaAjaxIntoDiv

Feel free to Demo the above code below...

cooltext439924698

Tuesday, December 22, 2009

Performance of JavaScript Looping Techniques

I was reading Paul Irish’s (@paul_irish) recent blog post entitled Updates from all around – Dec 2009 and I saw an interesting for loop syntax that he referenced…

for (var i = -1, len = arr.length; ++i < len; ) // the cool guy loop

He went on further to show some performance results of the above syntax compared to the old for loop style most of us are used to.

I thought this was interesting, so I decided to put my own suite of tests together to exercise various looping techniques and determine their average performance. 

Note: In my test methods I wanted to simulate a semi-real world scenario where an array would be used and in the loop an item from the array would be referenced.

The test runner accepts the size of the array to be looped and the number of times you want the test to be ran. The end result will print the average time (in milliseconds) the test took to the console.

Here are the functions that I am profiling…

function oldAndBusted() {
   for (var i = 0; i < arr.length; ++i) { arr[i]; }
}

function oldAndBustedCached() {
   var arrLength = arr.length;
   for (var i = 0; i < arrLength; ++i) { arr[i]; }
}

function coolGuyLoop() {
   for (var i = -1, len = arr.length; ++i < len; ) { arr[i]; } 
}

function coolGuyLoopCached() {
   var arrLength = arr.length;
   for (var i = -1, len = arrLength; ++i < len; ) { arr[i]; } 
}

function whileLoopCached() {
   var i = 0, arrLength = arr.length;
   while (i < arrLength) { arr[i]; i++; }
}

function reverseWhileLoop() {
   var i = arr.length; 
   while (i--) { arr[i]; }
}

Here are the results of my testing...

JavaScriptLoopPerformance2

You can view, run, and edit the tests for yourself on JS Bin (jsbin.com/uvoye/edit)

From a speed perspective here is how the various looping techniques ranked against each other (#1 being fastest & #6 being slowest)

  1. Reverse While Loop
  2. The Cool Guy Loop
  3. Old and Busted Cached
  4. While Loop Cached
  5. The Cool Guy Loop Cached
  6. Old and Busted
    I was actually surprised that ‘the cool guy loop cached’ was slower than ‘the cool guy loop’. I was thinking if I saved off the array length into a variable that it would speed up the loop instead of accessing the length every time.
    Note: If you have any variations of a loop you would like to see in my test cases, please provide a comment with your suggestion.

cooltext439924698 cooltext439925164

Note: The above performance times were ran using FireFox 3.6 Beta 4 using FireBug 1.5X.0b8 on an Intel Quad Core 2.00GHz Laptop running Win7.

Twitter Killed the jQuery Star

As many of you are aware, I am a frequent Tweeter and regularly distribute Web Developer technology related links for .NET and jQuery via my Tech Tweets.

Historically, my main concern was to just gather the latest web dev news and Tech Tweet those out to the public.

However, more and more many of these posts are just round-ups of other posts with little or no commentary. These posts tend to clutter the interwebs with noise that makes it difficult to find the real gems of web development. 

A combination of a recently article entitled Smashing Magazine Killed The Community (Or Maybe It Was Me) and the input of several individuals that I respect inspired me to change how I am Tech Tweeting.

I put out an informal poll on Twitter and here were the results…

TopjQueryPluginPoll

The funny thing is that most of the responses were either in total support of the posts or in total opposition to the posts.

So what now? That is a good question. I’m not sure if you have noticed, but I have dramatically decreased the amount of round-up posts that I tweet.

If a blog post matches one or more of the following criteria it is most likely not going to be tech tweeted anymore…

  1. The title of the blog post starts with a number (example: “Top 10 jQuery Plug-in…”)
  2. If the blog post contains a series of screenshots from other websites without any original content
    Over the past couple of weeks I have been saving jQuery posts that I’ve not tweeted matching the above criteria. Thus far I have 22 rejected blog posts!

For those of you who voted that you liked the round-up posts, I still plan to post those blog posts, but only those that are of the highest quality and hopefully provide some sort of original content such as sample code, pros & cons, personal thoughts, etc…

My goal is to aid the jQuery community, not work against it ;)

Note: If you have any feedback about the above post or how I can improve Tech Tweets, please let me know.

Now for listening enjoyment...

Monday, December 21, 2009

Year End Twitter Cloud

TwitterCloud2009Small3

To end off the year, I thought I’d generate a quick Tweet Cloud that represents my top word usage on Twitter.

I think the above image pretty much sums up my presence on Twitter ;) As if you didn’t know before, I mostly tweet about ASP.NET MVC, jQuery, and general Web Dev related topics.

The above graph was generated by TweetStats and then passed through a service called Wordle.

Note: You can also generate Twitter Clouds using the TweetCloud service, but I found that it wasn’t as accurate at the TweetStats service that I used above. For example, TweetCloud didn’t list ASP.NET MVC as one of my top Twitter words, whereas TweetStats did. Maybe TweetCloud doesn’t account for hashtags?

I hope you have a great Christmas and a New Year!

Friday, December 18, 2009

Tools of the Tech Tweet Trade

TechTweetBird I get a lot of questions about how I go about finding and distributing my Tech Tweets on a day to day basis. Some people even have the notion that I just sit at my computer and tweet all day.

I thought I’d put together some of these questions and answer them for you. The process is ongoing and regular changes, but the following will capture what I am doing today.

Before we start going into the logistics of what I use and how I use it, I thought I’d first give you a quick overview of why I started tech tweets and why I continue to provide them.

So, without further ado, here are the questions…

1. Why did you start doing Tech Tweets?

I’ve always been a sucker for the latest and greatest technologies. Not only do I enjoy finding out about the latest news and tools, but I also enjoy learning more about my current craft and becoming a better programmer. For these reasons, I regularly sorted through a wide variety of RSS feeds looking for what’s new.

At first, I just kept those links to myself and tried to build my craft. As time progressed I thought my teammates at work might benefit from the links I’ve found as well.

Shortly after, I became aware of Twitter where I was able to take a peak into the minds of those that I admire (in the programming world). Then I figured maybe someone outside of my team might benefit from the links, so I started tweeting them. At first I thought it would also be helpful for me to search for my old tweets, but I later found out that the Twitter search doesn’t go back all that far (in my case like 3 weeks).

2. How do you find all the information for you Tech Tweets?

Tweetie2_320 reader twitter_256x256 194beddda84293e00a3a25b0989

I use a variety of tools to help round up the latest Tech Tweets. One of my main tools happens to by my iPhone. While I am out, I often get on Tweetie and search Twitter for jQuery and ASP.NET MVC related information. When I find an interesting article, I will post the tweet to Instapaper. A long time ago I used to favorite tweets, but I like the concept of marking Instapaper entries as read (kind of like you do in e-mail). So, Tweetie is one of the iPhone Twitter apps that has integration with Instapaper.

Once I get access to my main computer, then I move on to Google Reader to check my daily RSS feeds (of which I currently have 227 subscriptions even after removing quite a few of them last week). If you don’t have it already, there is an awesome extension for Google Reader (Google Reader Plus for Google Chrome or Google Reader Filter for Firefox’s GreaseMonkey) that will allow you to filter your feeds via Regular Expressions. You can list RegEx patterns that you like and RegEx patterns that you don’t like. The one you like will be highlighted in yellow and the ones you don’t like will be grayed out. You can also set some other options like remove duplicates!

3. What tools do you use to distribute your Tech Tweets?

BigTweetLogo
windows-live-writer
delicious_256x256 hootsuite-icon

I would say that this area is the one that I change most frequently, but as of now I start by using a bookmarklet called BigTweet to capture my Tech Tweets. The bookmarklet overlays an inline modal onto the webpage you are on and captures the title of the page, auto shortens the URL using j.mp (formerly bit.ly), and it even can auto post to delicious if you want. There are many other features as well so I recommend you check it out.

So, instead of posting directly from BigTweet to Twitter, I copy/paste the results into HootSuite where I schedule the tech tweet to send out at a future time. I have used many scheduling Twitter clients in the past such as Twuffer, TwitterMatic!, FutureTweets, TwtMstr, Social Oomph (formerly known as Tweet Later), but I’ve found that HootSuite has given me the nicest UI, the richest features, with consistent results. And now recently they have released an iPhone version that uses the same settings you have in the browser version! The one thing that I resist from HootSuite is their URL shortener. I used it for a little while, but soon found out that people didn’t like the digg like bar at the top of each tech tweet I sent out ;)

After the tech tweets have gone out for the day, I use Window Live Writer (WLW) to post a daily Tech Tweet round-up. I wrote a plug-in for WLW to gather my Tweets from today, group them into categories, parse them with a Regular Expression, expand the URLs, submit the Tech Tweets to my delicious account for future searching, and then generate the HTML for the Tech Tweet blog post.

Conclusion

You might have noticed that I have slightly changed my approval process over the last week or two. I am trying to refine my process to keep the highest quality links as possible and cut out the noise. I plan to do a separate post on my thoughts about this later.

I hope you have enjoyed the Tech Tweets and I plan to continue to provide helpful, timely, and high quality links on a day to day basis.

If you have any suggestions on how I can better contribute to the community through Tech Tweets please let me know. I value your input!

Thursday, December 17, 2009

Where Did @elijahmanor’s Tech Tweets Go?

TechTweetBird You might be wondering “Where Did @elijahmanor’s Tech Tweets Go?”. I actually wasn’t aware of this issue until I had several people asking where my tech tweets went. It seems that there is an issue with my account on Twitter today starting around 9AM CST.

In order to see my tweets there is a workaround of unfollowing and then refollowing me (@elijahmanor). This seems strange, but it has worked for those that have tried it.

You may have not noticed that this was a problem. If that is the case then maybe you were seeing my tweets as part of a Twitter search (which still works) or maybe I was part of a custom Twitter List that you are watching.

I hope that this is just a temporary glitch in Twitter that will resolve itself soon. I have created a Twitter Ticket explaining the issue just in case.

I will do my regular Tech Tweets blog post round-up as usual. So, if you didn’t see any of my tech tweets you can enjoy them there :)

Update: On my way home today I noticed an update to the Twitter Status Blog stated that

We are aware of and investigating the causes of timeline delays and missing tweets. Retweet is back up and fully functional.

So, I hope that means this will not last for long ;)