SoFunction
Updated on 2025-04-04

Yii2 Methods to load static resources in css and js

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

&lt;?php
$this-&gt;registerJs("
  $(function () {
  //Write the js code you want to write for whatever you want  
  });
", \yii\web\View::POS_END);

Plan 2

&lt;?php $this-&gt;beginBlock('js') ?&gt; 

  //js code  
&lt;?php $this-&gt;endBlock() ?&gt; 
&lt;?php $this-&gt;registerJs($this-&gt;blocks['js'], \yii\web\View::POS_END); ?&gt; 

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!

&lt;script type="text/javascript"&gt;
&lt;?php $this-&gt;beginBlock('js') ?&gt; 

  //js code  
&lt;?php $this-&gt;endBlock() ?&gt; 
&lt;?php $this-&gt;registerJs($this-&gt;blocks['js'], \yii\web\View::POS_END); ?&gt; 
&lt;/script&gt;

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.