Yii2 - Include JS Script Only For Specific View

落花浮王杯 提交于 2019-12-10 02:31:01

问题


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 included in every page.

For including a js script for the whole site I normally have to edit AppAsset.php. For this purpose, what should I do?


回答1:


You should simply register this js file in your view, e.g. :

$this->registerJsFile('@web/js/specific.js');

Read more : http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html#registering-scripts




回答2:


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:

<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @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




回答3:


@soju is right. But you also can create specific asset bundles for use specific views. Your specific js files can be a file group on this situation you can use asset bundles and can use any views which you want.



来源:https://stackoverflow.com/questions/28781463/yii2-include-js-script-only-for-specific-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!