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...