Rails No-No’s: Using inline CoffeeScript with Haml
I’ve always had a love-hate relationship with HAML, partly because if the css is clean, it can be a great thing, and if it isn’t then your markup will look really ugly. But that is not the thing I’m writing about now. This is about something else, using inline CoffeeScript inside Haml templates. As you know, you really shouldn’t be using inline JavaScript at all, but you can get by, especially if you have some weird use cases. The thing with CoffeeScript is that it has to get compiled each time into JavaScript, which is fine, if you are using something like Sprockets to compile it on deployment, but if you are using the feature Haml provides you to shoot yourself in the foot, you can cause some serious performance issues for your site.
Consider the two following snippet:
If you put that in the template, you are causing yourself with a hit of about 100-200ms that takes to compile that coffescript into javascript, and then inline it. But if you try doing this:
Then the performance hit is mostly gone. You still have a code smell in your views, but not a one that will cause a drastic performance loss if you don’t remove it right away.
But if you consider a situation in which you render nested partials, and each one of them has some inline coffeescript, which I myself have done unknowingly before, that will multiply the issue with the amount of rendered partials. You can of course count on rails caching to save your ass, and it will most of the times, but not always. And then you will have that one customer who waits for more than 10 seconds to get their page.
If by any means you want to reduce the maintenance nightmare, you will be very fast to remove inline javascript from the code all together, which will most probably also optimise your javascript code, and make it more maintainable in the future.
Comments