On Thu, Mar 20, 2008 at 12:44 PM, KREYCHE, MICHAEL <[log in to unmask]> wrote:
> > -----Original Message-----
> > From: Code for Libraries [mailto:[log in to unmask]] On
>
> > Behalf Of Godmar Back
> > Sent: Thursday, March 20, 2008 10:45 AM
> > To: [log in to unmask]
> > Subject: Re: [CODE4LIB] Google Book Search API - JavaScript Query
> >
>
> > Have you tried placing your code in an window.onload handler?
> > Read the example I created at libx.org/gbs and if that works
> > for you in IE6, use the technique there. (Or you may just use
> > the entire script - it seems you're reimplementing a lot of
> > it anyway.)
>
> I'll have to study that a bit and see how it works. I was aiming for a
> solution with a minimal amount of code, but perhaps a more robust
> approach like yours is in order.
>
I looked into this issue some more and like to share a bit of what I learned.
The short answer is: use jQuery (or a library like it.)
The longer answer is that window.onload - even the browser-compatible
version using the addEvent function described here:
http://www.dustindiaz.com/rock-solid-addevent/ ) won't fire until all
images on a page have loaded, which can incur significant latency -
especially if there's a large number of embedded objects from
different origins on the page, some of which may be stragglers when
loading.
Instead, what you want is a browser-compatible notification when the
HTML content has been downloaded and parsed into the DOM tree
structure, that is, when the document is "ready" and it's safe to
manipulate it using such methods as getElementById(). Implementing
this notification requires a variety of browser-specific hacks (google
for details, or examine 'bindReady' in jQuery for a distilled summary
of the collective experience.)
jQuery implements those hacks and hides them from you, so in jQuery,
it's as simple as saying
$(function () { insert work here });
JQuery will determine when the document is ready and execute your
anonymous function then, which is at the earliest possible time. If no
hack is known for a particular platform, jQuery falls back to the
"load" handler.
If you think about it, that's not something you want to implement or
even think about.
(Note that jQuery's init constructor, which is what the $ symbol is
bound to, heavily adjusts to the type of its first argument. If the
argument is a function, it means to call the function when the
document is ready. An alternate syntax is $().ready(function ...) -
which relies on jQuery substituting 'document' if the first argument
is not given. The most readable syntax may be:
"$(document).ready(function ...)" though $(function ...) may make for
a good idiom.)
- Godmar
|