Registering Script In Jquery Ready Function Without Layout


it appears that registering a script like:

Yii::app()->clientScript->registerScript('script_id', $script, CClientScript::POS_READY);

won’t work unless a layout is present. I.e., if setting controller’s layout to [color="#FF0000"][font=“Courier New”]false[/font][/color] before rendering, the script will be included at the end of the resulting file, outside the jQuery ready function…

Does anyone know how to overcome this inconvenient? Should it be considered a bug?


PS: proper inclusion of the script inside jQuery ready function relies on the BODY tag.

PPS: this are the relevant lines in CClientScript.php


if ($fullPage)  // this will be true when the body closing tag was previously matched

    $scripts[] = "jQuery(function($) {\n".implode("\n",$this->scripts[self::POS_READY])."\n});";


    $scripts[] = implode("\n", $this->scripts[self::POS_READY]);

Why is it coded this way?

Hi clapas

without layout test this:


best regards

Thanks KonApaz,

I think that method is already called by [font="Courier New"]CController::render()[/font].

I found a solution for my problem. I plan to write a wiki article with a thorough explanation about this, but I will summarize here what I was attempting and fortunately finally accomplished.

I have a model called Task which includes title, a priority, a requester type, etc. There is an associated controller called [font="Courier New"]TaskController[/font], as you may expect. Obviously there is an index action, where I list the tasks.

Nothing special so far. But here comes the key of this topic: I want a dashboard action in my site controller to render some of the tasks from the index, e.g. the most recent 5 tasks. But I don’t want my site controller to know all the logic needed to display the proper tasks (there are role concerns among others).

What I ended up with is an action class, [font="Courier New"]TaskIndex[/font] which can be called from both the task controller and the site controller.

The problem arouse with the scripts, because my site controller wants the TaskIndex action to render the content without layout, but then no body tag was present and the javascript wasn’t properly included inside the jQuery ready function, as I already stated in the opening post.

I solved this simply wrapping the call to the [font="Courier New"]TaskIndexAction[/font]:

Yii::app()->clientScript->enableJavaScript = false;

$this->runAction(new TaskIndex($this, 'index'));

Yii::app()->clientScript->enableJavaScript = true;

The script is still registered, so when the site controller finally renders its view, the scripts will be properly included inside the jQuery ready function.