Categories
Uncategorized

Prototype and window.onload

We’ve known for some time that simply assigning to window.onload is bad. Simon Willison created addLoadEvent a long time back to work around the problem. But I’m in Rails, and we have prototype. So what’s the correct idiom?

Well, after a bit of playing, it seems to be this:

  <% content_for("page_scripts") do %>
    Event.observe(window, 'load',
      function() { $('username').focus() }
    );
  <% end %>

I do love that $() function.

This assumes that you have a layout that looks something like this, in order to insert bits of JavaScript into the head.

  <script type="text/javascript">
    <%= @content_for_page_scripts %>
  </script>

Anyway, the solution seems a little more verbose than addLoadEvent(), but not disastrously so.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s