This article mainly introduces the method of loading css and js to load static resources in Yii2. It has certain reference value. Interested friends can refer to it.
Application Scenario
Yii2 provides the AppAsset class to manage static resources. When using the Yii2 layout template, if you want to write a piece of js inside a page and At the bottom of the page, it is not possible to use script tags directly.
Use the AppAsset class to manage static resources
Open assetsAppAsset.php and define addJs() and addCss() for introduction in static pages respectively External js, css files
1. Modify the AppAsset.php file code
namespace backend\assets; use yii\web\AssetBundle; /** * @author Qiang Xue * @since 2.0 */ class AppAsset extends AssetBundle { public $basePath = "@webroot"; public $baseUrl = "@web"; //默认自动加载样式 public $css = [ "css/site.css", ]; //默认自动加载js public $js = [ ]; //依赖关系管理 public $depends = [ "yii\web\YiiAsset", "yii\bootstrap\BootstrapAsset", ]; //定义按需加载JS方法,注意加载顺序在最后 public static function addJs($view, $jsfile) { $view->registerJsFile( $jsfile, [ AppAsset::className(), "depends" => "backend\assets\AppAsset" ] ); } //定义按需加载css方法,注意加载顺序在最后 public static function addCss($view, $cssfile) { $view->registerCssFile( $cssfile, [ AppAsset::className(), "depends" => "backend\assets\AppAsset" ] ); } }
2. Call AppAsset.php on the static page
<?php use backend\assets\AppAsset; AppAsset::register($this); AppAsset::addJs($this,Yii::$app->request->baseUrl."/js/a.js"); AppAsset::addCss($this,Yii::$app->request->baseUrl."/css/b.css"); ?>
Load the javascript code at the bottom of the website page
The js file or code inside the web page, according to The page loading sequence avoids the execution of js time process causing the page to be blank and causing poor user experience. Generally placed at the bottom of the web page behind
.
Option 1
<?php $this->registerJs(" $(function () { //为所欲为的写你想要写的js代码吧 }); ", \yii\web\View::POS_END);
Option 2
##
<?php $this->beginBlock('js') ?> //js代码 <?php $this->endBlock() ?> <?php $this->registerJs($this->blocks['js'], \yii\web\View::POS_END); ?>
##Solution to the problem that Yii2 loads JS at the bottom of the page and the syntax prompt fails
Just add the script tag. Note that only option 2 is valid. If you know of other methods, please let us know. Thank you!
<script type="text/javascript"> <?php $this->beginBlock('js') ?> //js代码 <?php $this->endBlock() ?> <?php $this->registerJs($this->blocks['js'], \yii\web\View::POS_END); ?> </script>
The above is the detailed content of Detailed introduction to the method of loading css, js and static resources in Yii2. For more information, please follow other related articles on the PHP Chinese website!