Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii - External JS files Inlclude , registerScriptFile and publish

Tags:

yii

I am using YII framework for my web application . I have a question on registering external Java script file.

Could some one please help me ?

  1. What is the best location to copy Java script file ( which folder )
  2. I do see there are two ways to register that external Java script file

    First approach

     $baseUrl = Yii::app()->baseUrl; 
     $cs = Yii::app()->getClientScript();
     $cs->registerScriptFile($baseUrl.'/js/yourscript.js'); 
    

    Second approch

     $cs=Yii::app()->getClientScript();
     $cs->registerScriptFile(Yii::app()->getAssetManager()->publish('path/to/js'));
     $cs->registerScript('id', 'your js here');
    

In the first approach I am directly registering with registerScriptFile and passing the java script file

In the second approach I am registering and publishing the script . That means it copies to assets folders. ( Please correct me If I am wrong ) and then what does the last step does, What is id and again java script file . ($cs->registerScript('id', 'your js here');)

In my case I am accessing it from one of the views , so in the second approach since it gets published to the asset folder , if 10 clients calls the file does it published 10 times ( since I am accessing it from the view file )

I am bit confused .

Thanks for your answer

Regards

Kiran

like image 463
Bujji Avatar asked Jan 19 '12 20:01

Bujji


2 Answers

Yii Assets folder is generally used by Widgets and Yii's internal components like Gridview. You don't need to store or publish your external JS or CSS files to assets folder.

Secondly if the files already exist in assets folder getAssetManager()->publish('path/to/js') will not copy it againg.

and last you don't need to instantiate CClientScript class, you can call it directly as

Yii::app()->clientScript->registerScriptFile(
    Yii::app()->baseUrl.'/js/file.js'
);

or if you are using themes

Yii::app()->clientScript->registerScriptFile(
    Yii::app()->theme->baseUrl.'/js/file.js'
);
like image 52
Uday Sawant Avatar answered Oct 21 '22 17:10

Uday Sawant


In common case the best way is to put your JS files into web_root/js and to use $cs->registerScriptFile. AssetManager convenient to use in widgets. You can put your JS files into protected folder, and publish them to the assets folder when it's needed. If you'll call publish() method 10 times, it should publish your files only ones. If you set $forceCopy parameter to true (default is false), then it whould copy 10 times, but in the same dir.

like image 33
Oleg Avatar answered Oct 21 '22 16:10

Oleg