Yii - 外部 JS 文件包括、注册脚本文件和发布 [英] Yii - External JS files Inlclude , registerScriptFile and publish

查看:18
本文介绍了Yii - 外部 JS 文件包括、注册脚本文件和发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的 Web 应用程序使用 YII 框架.我有一个关于注册外部 Java 脚本文件的问题.

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

有人可以帮我吗?

  1. 复制Java脚本文件的最佳位置是什么(哪个文件夹)
  2. 我确实看到有两种方法可以注册该外部 Java 脚本文件

  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

第一种方法

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

第二步

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

在第一种方法中,我直接使用 registerScriptFile 注册并传递 java 脚本文件

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

在第二种方法中,我正在注册和发布脚本.这意味着它会复制到资产文件夹.(如果我错了,请纠正我)然后最后一步做了什么,什么是 idjava script file .($cs->registerScript('id', 'your js here');)

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

在我的情况下,我从一个视图访问它,所以在第二种方法中,因为它被发布到资产文件夹,如果 10 个客户调用该文件,它会发布 10 次(因为我从视图访问它文件)

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 )

我有点困惑.

感谢您的回答

问候

基兰

推荐答案

Yii Assets 文件夹通常被 Widgets 和 Yii 的内部组件如 Gridview 使用.您无需将外部 JS 或 CSS 文件存储或发布到资产文件夹.

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.

其次如果assets文件夹中已经存在文件getAssetManager()->publish('path/to/js')不会再次复制.

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

最后你不需要实例化CClientScript类,你可以直接调用它

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

这篇关于Yii - 外部 JS 文件包括、注册脚本文件和发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆