Method for loading css and js static resources in Yii2, yii2css
Application scenarios
Yii2 provides the AppAsset class to manage static resources. When using the Yii2 layout template, if you want to write a js file inside a page and at the bottom of the page, you cannot directly use the script tag.
Use the AppAsset class to manage static Resources
Open assetsAppAsset. php and define addJs (). addCss () is used to introduce external js and css files on static pages respectively.
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"; // automatically loads the style by default. public $ css = ["css/site.css",]; // automatically load js public $ js = [] by default; // dependency management public $ depends = ["yii \ web \ YiiAsset ", "yii \ bootstrap \ BootstrapAsset",]; // defines the JS method to be loaded as needed. Note that the loading order is at the end of the public static function addJs ($ view, $ jsfile) {$ view-> registerJsFile ($ jsfile, [AppAsset: className (), "depends" => "backend \ assets \ AppAsset"]);} // define the On-Demand Loading css method. Pay attention to the loading order at the end of the public static function addCss ($ view, $ cssfile) {$ view-> registerCssFile ($ cssfile, [AppAsset :: className (), "depends" => "backend \ assets \ AppAsset"]);}
2. Call AppAsset. php on the Static Page
<?phpuse 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 javascript code at the bottom of the website page
Js files or code inside the webpage should be loaded according to the page order to avoid blank pages due to execution of js time, resulting in poor user experience. Usually placed behind the bottom of the page </body>.
Solution 1
<? Php $ this-> registerJs ("$ (function () {// write the js Code you want to write whatever you want});", \ yii \ web \ View :: POS_END );
Solution 2
<? Php $ this-> beginBlock ('js')?> // Js Code <? Php $ this-> endBlock ()?> <? Php $ this-> registerJs ($ this-> blocks ['js'], \ yii \ web \ View: POS_END);?>
Solve Yii2 load JS at the bottom of the page, and the syntax prompt is invalid.
Add the script tag. Note that only solution 2 is valid. If you have other methods, please kindly advise. 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 for your learning and support for helping customers.