Yii2 - Include JS Script Only For Specific View

后端 未结 3 2354
醉梦人生
醉梦人生 2021-02-20 09:07

I want to include my js script specific.js for a specific view having action id specific-action-id. I don\'t want the specific.js to be in

3条回答
  •  孤独总比滥情好
    2021-02-20 09:26

    It is highly recommended to use asset bundles to register external JS files rather than registerJsFile() because these allow better flexibility and more granular dependency configuration. Also using asset bundles allows you to combine and compress multiple JS files, which is desirable for high traffic websites.

    So you can create a new AppAsset file and put your css and javascript files in it.

    Create the Asset Bundle

    In the \assets directory, we create StatusAsset.php:

    
     * @since 2.0
     */
    class StatusAsset extends AssetBundle
    {
        public $basePath = '@webroot';
        public $baseUrl = '@web';
        public $css = [];
        public $js = [
          '/js/jquery.simplyCountable.js',
          '/js/twitter-text.js',
          '/js/twitter_count.js',  
          '/js/status-counter.js',
        ];
        public $depends = [
                'yii\web\YiiAsset',
                'yii\bootstrap\BootstrapAsset',
            ];
    }
    

    In your view file

    use app\assets\StatusAsset;
    StatusAsset::register($this);
    

    Resources http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html https://code.tutsplus.com/tutorials/how-to-program-with-yii2-working-with-asset-bundles--cms-23226

提交回复
热议问题