问题
I have different CSS and JS files related to different views. How to load CSS and JS conditionally or dynamically according to views so that only the respective JS or CSS loads to the browser?
回答1:
It's simple. Just create condition on your function. Then send your CSS or JS file location to view.
Controller:
public function index() {
// conditional
if (your condition) {
$this->data = array(
'css' => site_url() . "your css file",
'js' => site_url() . "your js file"
);
} else {
$this->data = array(
'css' => site_url() . "your other css file",
'js' => site_url() . "your other js file"
);
}
$this->load->view('page', $this->data);
}
View:
<link rel="stylesheet" type="text/css" href="<?php echo $css; ?>">
<script src="<?php echo $js; ?>"></script>
回答2:
Add css and js files to the page from controller, and pass to view using data array. For loop the array and load css and java files from view. Example given below,
Controller section
$styles[1]['css'] = 'plugins/select2/select2.css';
$styles[2]['css'] = 'plugins/datatables/plugins/bootstrap/dataTables.bootstrap.css';
$data['styles'] = $styles;
$scripts[1]['js'] = 'plugins/select2/select2.min.js';
$scripts[2]['js'] = 'plugins/datatables/media/js/jquery.dataTables.min.js';
$data['scripts'] = $scripts;
View section
{if isset($styles)}
{foreach from=$styles item=v}
<link href="{base_url()}assets/{$v.css}" rel="stylesheet">
{/foreach}
{/if}
{if isset($scripts)}
{foreach from=$scripts item=v}
<script src="{base_url()}assets/{$v.js}"></script>
{/foreach}
{/if}
回答3:
$add_js = array(
'filename' => array(BASEJS.'themejs/bootstrap-fileinput.js'),
'type' => 'import',
);
$footer = array(
'set_title' => MAINTITLE,
'javascript' => $add_js,
);
$get_footer = $this->settings->set_footer($footer);
来源:https://stackoverflow.com/questions/35519301/how-to-load-cs-js-dynamically-in-codeigniter