Reputation: 113
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?
Upvotes: 3
Views: 3195
Reputation: 31
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>
Upvotes: 3
Reputation: 2983
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}
Upvotes: 2
Reputation: 1
$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);
Upvotes: 0