Last Updated on November 29, 2016 by admin

If your Marketing or SEO guy is out of control (and when are they not?), you may be finding yourself stuffing insane amounts of JavaScript into your Rails views in order to track page referrals, conversion rates and other Google or Yahoo SEO analytic data. Not good from an esthetic standpoint.

The solution is to use partials to partition the JavaScript SEO stuff off into a corner. Plus, it’s easier to reuse.

Say you need to add some JS optimization code that looks like this:


<!-- Google Website Optimizer Conversion Script -->
<script type="text/javascript">
 if(typeof(_gat)!='object')document.write('<sc'+'ript src="http'+
 (document.location.protocol=='https:'?'s://ssl':'://www')+
 '.google-analytics.com/ga.js"></sc'+'ript>')</script>
<script type="text/javascript">
 try {
 var gwoTracker=_gat._getTracker("XX-XXXXXXXX-X");
 gwoTracker._trackPageview("/XXXXXXXXXX/goal");
 }catch(err){}</script>
<!-- End of Google Website Optimizer Conversion Script -->

Just create a _google_opt_file1.html.erb file under app/views/shared and then call it in your view with


<%= render :partial => 'shared/google_opt_file1' if RAILS_ENV == 'production' %>

This kind of SEO script typically goes right before the </body> tag. And you only need this script to run on your production site, hence the if clause.

Another side effect is that it’s easier to search for all references to “shared/google_opt_file1” than for strings inside the JavaScript code itself.