[philiptellis] /bb|[^b]{2}/
Never stop Grokking


Thursday, January 07, 2010

Handling document.write in dynamic script nodes

As a performance junkie, I generally want my pages to be as fast as I can make them. When I control the entire page, that typically means going all out. As a web user, I get annoyed when the little spinner on my browser keeps spinning even though I know that all the essential content on my page has loaded. When I redesigned my website late last year, I decided to address this issue.

Now if you take a look at my homepage, you'll notice a bunch of external resources:
  1. My Yahoo! Avatar
  2. My twitter feed
  3. My delicious bookmarks
  4. My upcoming events
  5. My dopplr badge
  6. My flickr photos
That's resources from six services whose performance I cannot control, nor rely upon. They're also six components on my page that aren't critical to the content of my page, and if one of them were unavailable for some amount of time, that wouldn't really hurt the purpose of the page.

Now I've been working with dynamic script nodes for a very long time to do background loading of scripts, but in all those cases, those scripts played nicely with other things on the page, and had JSONP responses. Not all the resources that I use now have this behaviour, so I had to come up with something else. Let's go through them one at a time.

To start with, I just included the javascript that all these services told me to include. Since the Avatar is just an image, I just used an img tag and left it at that. I've also never seen any performance issues with my Y! Avatar. The other services, however, all went down at some point or the other, and all had to be included as javascript.

Twitter

I started with the twitter widgets page. I copied the code, and pasted it where I wanted the twitter widget to show up. It's a lot of code, but that was okay to start with:
<script src="http://widgets.twimg.com/j/2/widget.js"></script>
<script>
new TWTR.Widget({
  version: 2,
  type: 'profile',
  rpp: 4,
  interval: 6000,
  width: 250,
  height: 300,
  theme: {
    shell: {
      background: '#333333',
      color: '#ffffff'
    },
    tweets: {
      background: '#000000',
      color: '#ffffff',
      links: '#4aed05'
    }
  },
  features: {
    scrollbar: false,
    loop: false,
    live: false,
    hashtags: true,
    timestamp: true,
    avatars: false,
    behavior: 'all'
  }
}).render().setUser('bluesmoon').start();
</script>
I then had to figure out if I could easily move the code to the bottom of my document so that it didn't block the rest of my page's load. twitter tends to go down more often than any of the other services.

I read through the source code for widget.js and found out that it creates a DIV into which it writes itself, however, you can create the DIV yourself, and pass its id to the widget constructor. The new code becomes:
<script src="http://widgets.twimg.com/j/2/widget.js"></script>
<script>
new TWTR.Widget({
  version: 2,
  type: 'profile',
  rpp: 4,
  id: 'twitter_widget',
  interval: 6000,
  width: 250,
  height: 300,
  theme: {
    shell: {
      background: '#333333',
      color: '#ffffff'
    },
    tweets: {
      background: '#000000',
      color: '#ffffff',
      links: '#4aed05'
    }
  },
  features: {
    scrollbar: false,
    loop: false,
    live: false,
    hashtags: true,
    timestamp: true,
    avatars: false,
    behavior: 'all'
  }
}).render().setUser('bluesmoon').start();
</script>
I could then create a DIV with an id of twitter_widget where I wanted the widget to go, and push the twitter code to the bottom of my page. This worked well. Kudos to Dustin Diaz for building a flexible widget, but really, you need to make those API docs available somewhere in that widget.

Anyway, we'll get back to twitter later, let's move on.

delicious

Finding the delicious badge was the toughest part. It's hidden on the help page under tools. Anyway, if you don't want to search for it, this is the link for delicious linkrolls.

After configuring the widget, I ended up with this javascript:
(I've split it onto multiple lines for readability)
<script type="text/javascript"
    src="http://feeds.delicious.com/v2/js/bluesmoon?
         title=My%20Delicious%20Bookmarks
         &icon=s
         &count=5
         &bullet=%E2%80%A2
         &sort=date
         &name
         &showadd"></script>
This code is not very nice, because I can't just move it elsewhere in the document. Looking at the page source, it seems that it initialises a Delicious namespace, and then loads two other javascript files. The first handles rendering of the linkroll, and the second is a JSONP feed of my links. Unfortunately, the first script chooses to write to the document using the document.write() javascript function.

Note that this function is the primary reason for javascript blocking page rendering -- it can modify the structure of the page as it loads. I decided to tackle this later.

Upcoming

Upcoming's badges are linked to from the page footer, so it was easy to start with this. I got the code, but decided to style it myself. The code points to the following javascript file (again wrapped for readability):
http://badge.upcoming.yahoo.com/v1/?
    badge_type=user
    &badge_size=sm
    &badge_layout=v
    &badge_styling=2
    &badge_no_background=
    &badge_venue=1
    &date_format_type=us_med
    &id=54783
The source of this badge shows that it also uses document.write() to write itself into the document. Solving this problem would tackle upcoming and delicious as well.

Dopplr

Dopplr was next, and was by far the easiest to work with. The account section points to a Blog badge which gives you a bunch of javascript to include onto your page among other things. The javascript link for my account is:
http://www.dopplr.com/blogbadge/script/6d1f4effa8fc5ac6db60160860ece8be?
    div-id=dopplr-blog-badge-for-bluesmoon
And the source code of that script had a lot of comments saying exactly what you can do with it. Brilliant. I just created a DIV with an id of my choice, and pushed this script to the bottom of the page.

Flickr

After the Avatar, delicious and upcoming, Flickr was the fourth Yahoo! property on my page. The previous two had already proved bad players, so my hopes weren't too high. Still, flickr has been good in the past, so I looked into it. The flickr badge page has a wizard to create the badge for you. This got me the following javascript:
http://www.flickr.com/badge_code_v2.gne?
    count=10
    &display=random
    &size=s
    &layout=x
    &source=user
    &user=57155801%40N00
Looking at the source of that showed the same old problem. document.write()

It was time to tackle this beast.

document.write()

To handle document.write(), I had to redefine what it did so that it would work asynchronously even after the entire page had loaded. I came up with this javascript:
document.writeln = document.write = function(s) {
 var id='';
 if(s.match(/\bupcoming_badge/)) {
  id='upb_events';
 }
 else if(s.match(/\bflickr_badge_image\b/)) {
  id='flickr_badge_wrapper';
 }
 else if(s.match(/\bdelicious\b/)) {
  id='delicious_widget';
 }
 else {
  id='overflow_div';
 }

 document.getElementById(id).innerHTML = s;
 return true;
};
It checks the content of the HTML to be written, and if it matches one of the three badges that I expect, I write it into the innerHTML of a DIV that I've already created for that badge. If it's something I don't recognise, then I assume that it doesn't matter where on the page it shows up, so just write it to an off-screen DIV.

I also had to make sure that there was no javascript being written out -- which is what the delicious badge was doing. In that case, I included the resulting javascript instead of including the javascript that the badge gave me.

Asynchronous loading

This worked, except that badges were still loaded in the order that I included the javascript, and if one blocked, all the others would wait, so I needed to make things asynchronous. This was easily accomplished using dynamic script nodes and handling the onreadystatechange event.

With this solved, I decided to parallelise downloads by moving all the code back into the head of the document. That way the script nodes would download in parallel with the document. Unfortunately, that also meant that some scripts might load up before the DIVs they need are available. Only dopplr handled this case well. For all the others, I had to handle it.

I ended up changing the write function above to defer until the required DIV was available.

Rather than include the entire Javascript here, I'll point you to the source file that you can see for yourself. It's not commented, but it's fairly small, so if you already know javascript, it should be easy to read.

With that, I had five badges on my page, all loaded asynchronously, and in parallel with each other and the page itself. My entire page is now reduced to four synchronous components: The HTML, CSS, Javascript and Avatar image (and possibly the favicon). Everything else is loaded asynchronously in the background and affects neither the firing of my onload handler, nor the browser's spinner.

You can see it in action on bluesmoon.info. Go ahead and view source.

Short URL: http://tr.im/docwritedynscr

8 comments :

Reehdust
January 08, 2010 1:46 AM

You can't innerHTML script nodes in IE.

So, a document.write('<script src="jsfile"></script>'); wouldn't work in 60% of the internet ;)

Blues
January 08, 2010 1:49 AM

@Reehdust: Actually you cannot do that in any browser, and I don't do it anywhere in my code. The only API that writes out more script nodes is delicious, so I actually skip the API, and use the resulting script nodes instead.

Reehdust
January 08, 2010 1:52 AM

Looks like Firefox allows script nodes injected through innerHTML.

Yeah, I can now see the delicious part.

Blues
January 08, 2010 1:56 AM

Cool, must be something new. I know that you could add script nodes as innerHTML, but they were never executed, or maybe I'm confusing it with putting full javascript code into an innerHTML.

Reehdust
January 08, 2010 2:15 AM

This YUI Plugin "Dispatcher" from the bubbling library by Caridy Patino serves similar purpose, but for Ajax content - http://www.bubbling-library.com/eng/api/docs/plugins/dispatcher

Satya Prakash
February 15, 2010 9:33 AM

I think instead of doing all these better to work on this kind of code:
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
})();

This google is using. we can write a function and pass the file url to it.

Satya Prakash
February 15, 2010 9:34 AM

Your blog is hosted on blogspot. so you do not have to worry much. I moved it to hosted one. and I need to pay and think of bandwidth. :(

Blues
February 16, 2010 11:18 AM

@Satya: The google method is insufficient for all types of widgets. It won't work with any widget that does a document.write internally. My method covers all types of widgets. It is a superset of the function that you mention in your comment.

I'm not sure what the issue with bandwidth is. Your users download the widgets directly from the service providers. You include a little javascript on your host, but if you set your caching headers correctly, this only needs to be downloaded once.

Post a Comment

...===...