Purpose of registerScript()

Hello!

newbie here.

i’m curious about the purpose of registering a javascript via YII’s “registerScript()” instead of writing it directly on the view. i compared both and it does the same thing except the former adds a CDATA around the script.

the class reference doesn’t explain much, so i’m wondering if anyone here can enlighten me?

Thanks!

  1. When using registerScript you can call this method at the top of a view and decide where to output the js-code.

POS_BEGIN, POS_HEAD …

or even POS_LOAD = window.onload

You don’t have to care about to output the code at the correct position.

  1. If you use POS_READY you don’t have to care about publishing jQuery.js and write the document.ready code manually

  2. Calls ‘recordCachingAction’ to support page caching

ahhh. ok. that makes much more sense now! Thanks Joblo :)

You can add some javascript code to a page from anywhere (e.g. inside a widget), and, as mentioned above, to put it at different positions on a page.

What is the best way to format my JS code in the registerScript function? For example, because the code has to be written within a string, this means that I lose stuff like syntax highlighting in my text editor.