本文主要是介绍[Yii2] Yii2单独加载CSS和JS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Yii2 使用用AssetBundle来管理资源,这个暂且不表。
上面的方法通常是在layouts文件中进行注册,这将无法处理需要单独加载的CSS,JS样式。
单独使用CSS:
$cssString = ".main{display:block;}";
$this->registerCss($cssString);
单独使用js:
<?php $this->beginBlock('test') ?> function hello(){console.log('hello');}
<?php $this->endBlock() ?>
<?php $this->registerJs($this->blocks['test'], \yii\web\View::POS_END); ?>
或使用类似上面css的方法:
<?php
$js = 'console.log('hello')';
$this->registerJs($js);
?>
但是上面的方法仍然面临较大的局限性,在多数情况下单独引入文件无疑是更加合适的方式:
//注册资源包
AppAsset::register($this);$this->registerCssFile('@web/style/style.css',['depends'=>['backend\assets\AppAsset']]);
$this->registerCssFile('@web/style/style.css');$this->registerJsFile('@web/script/jquery.js',['depends'=>['backend\assets\AppAsset']]);
$this->registerJsFile('@web/script/jquery.js'); //添加POSITION定义 文件的出现位置
$this->registerJsFile('@web/script/jquery.js',['depends'=>['backend\assets\AppAsset'],'position'=>$this::POS_HEAD]);
/*** @event Event an event that is triggered by [[beginBody()]].*/const EVENT_BEGIN_BODY = 'beginBody';/*** @event Event an event that is triggered by [[endBody()]].*/const EVENT_END_BODY = 'endBody';/*** The location of registered JavaScript code block or files.* This means the location is in the head section.*/const POS_HEAD = 1;/*** The location of registered JavaScript code block or files.* This means the location is at the beginning of the body section.*/const POS_BEGIN = 2;/*** The location of registered JavaScript code block or files.* This means the location is at the end of the body section.*/const POS_END = 3;/*** The location of registered JavaScript code block.* This means the JavaScript code block will be enclosed within `jQuery(document).ready()`.*/const POS_READY = 4;/*** The location of registered JavaScript code block.* This means the JavaScript code block will be enclosed within `jQuery(window).load()`.*/const POS_LOAD = 5;/*** This is internally used as the placeholder for receiving the content registered for the head section.*/const PH_HEAD = '<![CDATA[YII-BLOCK-HEAD]]>';/*** This is internally used as the placeholder for receiving the content registered for the beginning of the body section.*/const PH_BODY_BEGIN = '<![CDATA[YII-BLOCK-BODY-BEGIN]]>';/*** This is internally used as the placeholder for receiving the content registered for the end of the body section.*/const PH_BODY_END = '<![CDATA[YII-BLOCK-BODY-END]]>';
这篇关于[Yii2] Yii2单独加载CSS和JS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!