Yii - External JS files Inlclude , registerScriptFile and publish

若如初见. 提交于 2019-12-21 04:08:41

问题


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


回答1:


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'
);



回答2:


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.




回答3:


This question is answered already - https://stackoverflow.com/a/19210733/2670583 See more CClientScript for Yii



来源:https://stackoverflow.com/questions/8933024/yii-external-js-files-inlclude-registerscriptfile-and-publish

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!