Skip to content

Yii Tutorial : How to Add JavaScript into your views ?

Last updated on February 10, 2018

This post is about registering inline and external javascript files into views, Yii provided CClientScript to manage the scripts and CSS files in Yii application.

How to Register or add External java script files :

Here Script file located at webroot/resources/js., Yii::app()->baseUrl will return app base url.

       Yii::app()->clientScript->registerScriptFile(
        Yii::app()->baseUrl . '/resources/js/script.js',
	CClientScript::POS_END
	);

How to Register or add inline java script:

       Yii::app()->clientScript->registerScript(
        'my-welcome-grettings',
        'var greetings = "Hello" + " " + "World";
         alert(greetings);',
       CClientScript::POS_END
      );

Script Positions

CClientScript::POS_HEAD: The script is inserted in the head section right before the title element.
CClientScript::POS_BEGIN: The script is inserted at the beginning of the body section.
CClientScript:: POS_END: The script is inserted at the end of the body section.
CClientScript::POS_LOAD: The script is inserted in the window.onload() function.
CClientScript::POS_READY: The script is inserted in the jQuery’s ready function.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments