AJAX on page load


#1

Ok, I’m missing something obvious but after some reasonable looking in
The
Rails book (sorry haven’t gotten the cookbook yet) and these archives I
don’t see a solution to my question.

Question:
What is the cleanest way to load a div via AJAX when the page loads - no
user action necessary. I don’t really want to hack in a hidden remote
form
or link that is submitted or clicked on page load.

Also:
I like the thought of using AJAX vs partials or something since then I
can
cache this widget separately and use on multiple pages.


#2

On Mon, Feb 13, 2006 at 11:15:40PM -0500, Byron S. wrote:
} Ok, I’m missing something obvious but after some reasonable looking in
The
} Rails book (sorry haven’t gotten the cookbook yet) and these archives
I
} don’t see a solution to my question.
}
} Question:
} What is the cleanest way to load a div via AJAX when the page loads -
no
} user action necessary. I don’t really want to hack in a hidden remote
form
} or link that is submitted or clicked on page load.

The J in AJAX is JavaScript. Whether you use the Rails helpers or not,
you
are using JavaScript with XMLHttpRequest. There are two ways of getting
JavaScript to execute on page load. The first, and most dependable, is
to
call it from the body tag’s onLoad handler. The second, and less
dependable
method is to embed the call in a script tag at the bottom of the HTML
page.
The onLoad handler is guaranteed to fire after the page has been
entirely
loaded and laid out. Embedded scripts are run when they are encountered
(or
any time thereafter, I believe, at the discretion of the browser, but
before the onLoad handler is called).

Of course, if you want to load a div when the page loads, it would make
a
great deal more sense to put the initial contents of the div directly in
the page rather than making a separate request for it.

} Also:
} I like the thought of using AJAX vs partials or something since then I
can
} cache this widget separately and use on multiple pages.

It sounds like you really want a helper method, actually.

} Byron
–Greg


#3

Great - thanks for the response.