Love the web

Love the web is a design, programming, and usability blog

Chunked transfer encoding and onDOMReady

Peter Dekkers 15 May 2009

The main benefit of chunked transfer encoding is that it progressively shows content while your HTML loads. Enter unobtrusive JavaScript and its often used "onDOMReady" event. Combine the two and the problem arises that you're waiting too long for the JavaScript to kick in, negating some of the benefits of the transfer encoding.

An example. Say that you have a long page with many images. If JavaScript is available, you want to make those images fade in the moment they load. The server is serving up the pages with chunked transfer encoding. First off you'd hide the images before they load, maybe by setting their CSS visibility property to "hidden". The following JavaScript would go into the HEAD section of the document, after any other CSS:

document.write("<style type='text/css'>\n"); document.write("img {visibility:hidden;}\n"); document.write("</style>\n");

Then, as the page loads you want each image to fade in the very moment that it's ready. There are a few options. You can either put some JavaScript just below the image tags in the document. Once the HTML document has been loaded that far, you can start working with the images, attach an onload function to them. That works against the idea of unobtrusive JavaScript entirely though. And it also makes you wait too long again, as you have to get past all the images to the inline JavaScript before it fires.

Another, better, solution is using an interval in JavaScript that will keep polling the DOM until it is fully loaded, and will alert you of any new elements as they get added. This would allow you to use unobtrusive JavaScript. A few libraries come with this built in, most notably YUI with its onAvailable event. jQuery doesn't have it built in, but there are some plugins that will add similar functionality. Sadly these plugins seem to require ID values to select elements and don't use jQuery's selectors to the fullest.

In any case, this last method allows you to simply include a JavaScript file in the HEAD section of the document that will attach some JavaScript to the onAvailable event. In our example, using some jQuery pseudo syntax:

$.onAvailable('img', function(){ $(this).load(function(){ $(this).fadeOut(0).attr("visibility","visible").fadeIn(); }); });

I'll write a jQuery plugin for it in the next few weeks and report back.

Read the next post - TinyMCE plugin: auto resize

Submit a comment

Submit comment