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...
Note: Using Inline JavaScript is a bad practice and it is not recommended. It can be used for demonstration purposes so that the demonstrator doesn't have to deal with 2 separate files at a time. It is recommended to write JavaScript code in a separate .
Using inline script tags makes your website or application more vulnerable to cross-site scripting (XSS) attacks. You can avoid this JavaScript security risk by adding all your scripts, including inline event handlers (e.g. onclick ), as external . js files.
Inline JavaScript js and allows the browser to deliver a faster time to first render. However, note that inlining also increases the size of the HTML document and that the same script contents may need to be inlined across multiple pages. As a result, you should only inline small scripts to deliver best performance.
JavaScript is a very popular programming language used in lots of projects, also those in Ruby on Rails.
Sometimes inline JavaScript is useful for critical, fast views (e.g., certain landing pages), or small snippets (e.g., Facebook SDK initialization, Analytics/Kissmetrics initialization scripts, etc.) where using no external libraries can speed up page load. For those cases, I recommend using a partial _facebook.js.erb inside layouts, and define a helper:
module ApplicationHelper
def facebook_tag
content_tag :script, render(partial: 'layouts/facebook.js')
end
end
Then, create the file _facebook.js.erb and include the inline JavaScript inside application.html.erb using the defined helper:
<%= facebook_tag %>
For any other case, such as the partials you mention that inline JavaScript, I recommend using unobtrusive JavaScript as other answers suggest.
Best practice is to remove all inline javascript. However, there are 3 cases that I've run into where you absolutely need inline javascript:
If an image tag is referencing an image path that doesn't exist, the only way to prevent the image error from appearing (even in the web inspector) is to do this:
<img src="/i/dont/exist.png" onerror="$(this).attr("src", "/i/do/exist.png")" />
The following doesn't work because the onerror
event is executed before you even have time to grab the image with jQuery:
$("img").error(function() {
$(this).attr("src", "/i/do/exist.png")
});
The code below doesn't work either because the onerror
event doesn't bubble:
$("img").live("error", function() {
$(this).attr("src", "/i/do/exist.png");
});
So you have to use inline javascript for that.
If you wait until $(document).ready
to draw your feed of content into one of the empty container elements in your dom, the user will see the blank spot for a split second. This is why when your Twitter page first loads, the feed is blank for an instant. Even if you just put an external script file at the bottom of the dom, and in there you append the dynamically generated html elements to your page without even using $(document).ready
, it's still too late. You have to append the dynamic nodes immediately after the container element is added:
<script>App.bootstrap({some: "json"});</script>
<nav id='navigation'></nav>
<header id='header'></header>
<section id='content'>
// dynamic content here
</section>
<script>App.renderContent();</script>
<aside id='sidebar'>
// dynamically toggle which one is selected with javascript
<nav>
<h3>Search By Category</h3>
<ol>
<li>
<a href="/category-a">Category A</a>
</li>
<li>
<a href="/category-b">Category B</a>
</li>
</ol>
</nav>
</aside>
<script>App.renderSidebar();</script>
<footer id='footer'></footer>
If you're using JSON + javascript templates, it's a good idea to bootstrap the first set of data into the response body by including it inline in the page (in the above dom example too). That makes it so you don't need an additional ajax request to render content.
Rails has a lot of javascript helpers, and thankfully in Rails 3 most (all?) of it is unobtrusive; they're now using the data-
attribute and an external rails.js
file. However, many of the gems out there that are part-ruby part-javascript tend to still write helper methods add complex javascript inline:
That's helpful, but I think just having a clear README describing how to add the javascript to your application.js
is even more useful. External javascript makes it a lot easier to customize/extend the functionality down the road, it gives you a lot more control over the system, and it minimizes duplication across your html pages (so the response body is smaller, and the browser can cache external javascript files). Unless you need to handle missing images, instantaneous rendering, or bootstrap some json, you can put everything else in external javascript files and never have to use Rails javascript/ajax helpers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With