Where to put javascript snippets

For example if I have link and I want to add some javascript for onclick event what would be the best place for that?

I have couple locations on my mind but I want to hear how do you people handle this.

I was thinking:

  • to put it in a separate file but that would be overhead, I don’t want to create new request for small snippet

  • to put it in a controller code, but it doesn’t seem right to me, it should be in a view as it is part of presentation logic

  • to put it in a <script> tag inside view, but code will block page rendering until it executes and thus it’s not a good practice

  • to create ClientScript widget that will register script

I think the best solution for this would be to use ClientScript widget for small amount of javascript code or to use separate file for more.

sooooo, what did you come up with? I’m running into a situation where I have some core javascript libraries and other places that just need a few small snippets…my views are starting to look messier than I had hoped…

Use separated files along with SmartOptimizer to avoid multiple requests, and ClientScript to register the ones that are dinamic, using CClientSCript::POS_END + $(document).ready(code) to avoid page block, that is what I do

Also theres this extension to replace SmartOptimizer, but I haven’t used yet