views:

1151

answers:

3

I'm kinda new to using Rails, and an app I am working on is progressing well - however I'm looking though the generated HTML and noticed things like...

<script type="text/javascript">
//<![CDATA[
Droppables.add(...);
//]]>
</script>

Sprinkled around the HTML, which of course matches up with places where I use:

<%= drop_receiving_element ... %>

What I'm wondering is... is there a better way to do this, or make it cleaner? Some of these script tags are coming from partials so putting them at the 'bottom of the page' doesn't really help in this situation.

Another option may be pushing all these 'tag blocks' into an array then writing them out in the application.rhtml file, but its still a bit messy...

+7  A: 

Well if you really want to use best practices...Do not use inline javascript. Keep your HTML, CSS and Javascript clean and seperated from eachother. Ideally the html file should be usable without CSS and javascript.

The cleanest way, imo, is to just build your app using plain html/css, and enhance it with unobtrusive javascript to provide a better user experience.

A pattern for this is to include all your JS files at the bottom of your page, and start running your code with functionality like onDomReady.

Based on the comments I would like to add some possible options to get you started:

  • JQuery
  • YUI
  • Prototype
Tomh
+1, and recommend JQuery or Lowpro
Andrew Vit
I realize this is the best practice in general, but I'm wondering about this from a Rails perspective. A lot of rails apps I have seen make use of these script generators which seem to just output script blocks where ever they are called...
Matthew Savage
A lot of asp.net developers make IE only websites, doesn't mean you should do that too. I would strongly consider not using such "helpers".
Tomh
+1  A: 

This bothered me for a while and I eventually came up with a two pronged approach.

If you are developing a web application for a closed domain, where search engine performance and javascript are not an issue, just be pragmatic and let Rails' javascript helpers do their thing.

If you are developing for the web at large then do what Tomh sugested and code in plain html/css and then enhance onDomReady.

If you still want to use Rails helpers like button_to_remote that use inline javascript, then code your page load handler to send an Ajax request to the server. you can then use page.replace / page.replace_html to replace your regular page elements with code returned from the helpers.

Noel Walters
+1  A: 

I'd also recommend going with the unobtrusive Javascript approach and use jQuery.

For a great introductory tutorial on how to do that with Rails take a look at this jQuery + Rails screencast by Ryan Bates.

If you'd like to keep using helpers with jQuery, then take a look at a jRails, but if you do that, you'll still be violating the unobtrusive Javascript premise.

Dema