Application scenarios
Yii2 provides AppAsset class to manage static resources. When using Yii2 layout templates, 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 the script tag directly.
Manage static resources using AppAsset class
Open, define addJs() and addCss() to import external js and css files on static pages respectively
1. Modify the 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"; //Default automatic loading style public $css = [ "css/", ]; //The default automatic loading of js public $js = [ ]; //Dependency management public $depends = [ "yii\web\YiiAsset", "yii\bootstrap\BootstrapAsset", ]; //Define the loading method on demand, pay attention to the loading order at the end public static function addJs($view, $jsfile) { $view->registerJsFile( $jsfile, [ AppAsset::className(), "depends" => "backend\assets\AppAsset" ] ); } //Define the css method on demand, pay attention to the loading order at the end public static function addCss($view, $cssfile) { $view->registerCssFile( $cssfile, [ AppAsset::className(), "depends" => "backend\assets\AppAsset" ] ); } }
2. Call on static page
<?php use backend\assets\AppAsset; AppAsset::register($this); AppAsset::addJs($this,Yii::$app->request->baseUrl."/js/"); AppAsset::addCss($this,Yii::$app->request->baseUrl."/css/"); ?>
Load javascript code at the bottom of the website page
The js files or code inside the web page should be based on the page loading order, so as to avoid the page blanking caused by the execution of the js time, resulting in poor user experience. It is usually placed behind the bottom of the web page.
Plan 1
<?php $this->registerJs(" $(function () { //Write the js code you want to write for whatever you want }); ", \yii\web\View::POS_END);
Plan 2
<?php $this->beginBlock('js') ?> //js code <?php $this->endBlock() ?> <?php $this->registerJs($this->blocks['js'], \yii\web\View::POS_END); ?>
Solve Yii2 loads JS at the bottom of the page, and the syntax prompt fails
Just add the script tag. Note that only Solution 2 is effective. If you know there are other methods, please let me know, thank you!
<script type="text/javascript"> <?php $this->beginBlock('js') ?> //js code <?php $this->endBlock() ?> <?php $this->registerJs($this->blocks['js'], \yii\web\View::POS_END); ?> </script>
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.