具体操作如下:
(学习视频分享:编程视频)
1、在 assets/appasset 里定义方法
<?php/** * @link http://www.yiiframework.com/ * @copyright copyright (c) 2008 yii software llc * @license http://www.yiiframework.com/license/ */ namespace app\assets; use yii\web\assetbundle; /** * @author qiang xue <qiang.xue@gmail.com> * @since 2.0 */class appasset extends assetbundle{ public $basepath = '@webroot'; public $baseurl = '@web'; // 全局 public $css = [ ]; // 全局 public $js = [ ]; public $depends = [ // 'yii\web\yiiasset', // 'yii\bootstrap\bootstrapasset', // 注释掉禁用bootstrap ]; // 这是设置所有js放置的位置 public $jsoptions = [ 'position' => \yii\web\view::pos_head, ]; //定义按需加载js方法 public static function addjs($view, $jsfile) { $view->registerjsfile( $jsfile, [ appasset::classname(), "depends" => "app\assets\appasset" ] ); } //定义按需加载css方法 public static function addcss($view, $cssfile) { $view->registercssfile( $cssfile, [ appasset::classname(), "depends" => "app\assets\appasset" ] ); } }
2、在view里调用
<?php /* @var $this \yii\web\view *//* @var $content string */ use yii\helpers\html;use yii\bootstrap\nav;use yii\bootstrap\navbar;use yii\widgets\breadcrumbs;use app\assets\appasset; // 注册全局加载appasset::register($this); // 按需加载cssappasset::addcss($this, yii::$app->request->baseurl."/css/site.css");// 按需加载jsappasset::addjs($this, yii::$app->request->baseurl."/js/respond.min.js"); ?><?php $this->beginpage() ?><!doctype html><html lang="<?= yii::$app->language ?>"><head> <meta charset="<?= yii::$app->charset ?>"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <?= html::csrfmetatags() ?> <title><?= html::encode($this->title) ?></title> <?php $this->head() ?></head><body><?php $this->beginbody() ?> <?= $content ?> <?php $this->endbody() ?></body></html><?php $this->endpage() ?>
相关推荐:yii框架
以上就是yii2框架如何加载静态资源的详细内容。