Yii2.0對於CSS/js 管理,使用AssetBundle資源包類。javascript
視圖如何按需加載CSS/JS ?php
資源包定義:css
backend/assets/AppAsset.PHPjava
<?php namespace backend\assets; use yii\web\AssetBundle; /** * @author chan <maclechan@qq.com> * @since 2.0 */ class AppAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; //全局CSS public $css = [ 'css/animate.css', 'css/style.min.css', ];
//全局JS public $js = [ 'js/jquery-2.1.1.js' ];
//依賴關係 public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; //定義按需加載JS方法,注意加載順序在最後 public static function addScript($view, $jsfile) { $view->registerJsFile($jsfile, [AppAsset::className(), 'depends' => 'api\assets\AppAsset']); } //定義按需加載css方法,注意加載順序在最後 public static function addCss($view, $cssfile) { $view->registerCssFile($cssfile, [AppAsset::className(), 'depends' => 'api\assets\AppAsset']); } }
視圖中如何使用:jquery
<?php use yii\helpers\Html; use backend\assets\AppAsset; use backend\widgets\Alert; /* @var $this \yii\web\View */ /* @var $content string */ AppAsset::register($this);
查看源文件,看清CSS和JS的加載順序web
能夠看出以此順序爲:依賴關係 -> 自定義全局CSS/JSbootstrap
若是,某個視圖須要單獨引入一個CSS/JS,而且,在頁面中還要寫些CSS/JS,該如何作?
api
1,在頁面中單獨寫樣式:yii
$cssString = ".gray-bg{color:red;}"; $this->registerCss($cssString);
2,在頁面中單獨寫JS(使用數據塊)ui
<div id="mybutton">點我彈出OK</div> <?php $this->beginBlock('test') ?> $(function($) { $('#mybutton').click(function() { alert('OK'); }); }); <?php $this->endBlock() ?> <?php $this->registerJs($this->blocks['test'], \yii\web\View::POS_END); ?> <?php $this->registerJsFile('@web/inspinia/js/inspinia.js',['depends'=>['yii\bootstrap\BootstrapAsset']]) ?>
另外一種方式:
$this->registerJs( '$("document").ready(function(){ $("#login-form").validate({ errorElement : "small", errorClass : "error", rules: { "AgNav[id]": { required: true, }, }, messages:{ "AgNav[id]" : { required : "此字段不能爲空.", }, } }); });' );
在視圖中引入不是定義在全局裏的CSS或JS。
分別有兩種方法:
方法1,在資源包管理器裏面定義一個方法,而後在視圖中註冊便可(推薦使用這種)
如上面代碼己定義:
//定義按需加載JS方法,注意加載順序在最後 public static function addScript($view, $jsfile) { $view->registerJsFile($jsfile, [AppAsset::className(), 'depends' => 'api\assets\AppAsset']); }
視圖中使用以下:
AppAsset::register($this); //只在該視圖中使用非全局的jui AppAsset::addScript($this,'@web/js/jquery-ui.custom.min.js'); //AppAsset::addCss($this,'@web/css/font-awesome/css/font-awesome.min.css');
查看下源碼,特別的注意下,加載的順序,是咱們想要的結果
此外注意:在上面的addScript方法中,若是沒有 ’depends‘=>’xxx‘ ,此處加載的順序將會顛倒。
方法2,不須要在資源包管理器中定義方法,只要在視圖頁面直接引入便可
AppAsset::register($this); //css定義同樣 $this->registerCssFile('@web/css/font-awesome.min.css',['depends'=>['api\assets\AppAsset']]); $this->registerJsFile('@web/js/jquery-ui.custom.min.js',['depends'=>['api\assets\AppAsset']]); //$this->registerJsFile('@web/js/jquery-ui.custom.min.js',['depends'=>['api\assets\AppAsset'],'position'=>$this::POS_HEAD]);
//以上定義兩種有點區別,見下圖
加載在body區
加載在head中