Let's say I have a module of index (model view and controller).
On the index page I want to use a Highchart for example.
The simplest practise to do this is by including the highchart.js on my template.
But what if I don't want to include the highchart.js on my other pages?
If I include all of my plugins on the template it would be a waste and also the page could take a longer time to load. Is there any way in Codeigniter 3 to load the plugins only when needed?
This is completely your handle on which page, which plugin you have to load. You can include js, css dynamically. You can statically mention in all view page which js or css should include or you can pass over to controller.
Here is some reference. Hope it will help:
1) Codeigniter - how to include a dynamic javascript file in a view
2) how to load css, js dynamically in codeigniter
First categorised plugins to include in 3 (or more as number of plugins required) category:-
1) often used (included on 60-100% pages)
2) rarely used (included on 20-60% pages)
3) Once or not more than 2-5 pages
Create separate templates for first 2 category & include where you needed.
For last type include individually
In your template library add a function to load JS files:
public function set_js($name, $src)
{
$src = htmlspecialchars(strip_tags($src));
$this->_js[$name] = '<script src="'.$src.'"></script>';
return $this;
}
to be used as:
$this->template->set_js('js-file', base_url() .'assets/vendor/js-file/js-file.min.js');
in your controller.
In your layout you can then add
<?php print $template['js']; ?>
In the end I'm using HMVC and then I create my own core controller as MY_Controller and then under this class I write the function to get the plugins with the switch case.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends MX_Controller
{
public function __construct()
{
parent::__construct();
$this->load->module("Template");
}
public function include($plugin)
{
switch ($plugin) {
case 'highcharts':
return "global/plugins/js/highcharts.js";
break;
}
}
}
and then in my module controller I extend the core controller and then I put it in an array so if I have more than 1 plugin I can include them in the array.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Ookla extends MY_Controller {
public function index()
{
$data["js"] = [
$this->include('highcharts') // <- here
];
$data["main_content"] = "ookla/ookla";
$this->template->master_template($data);
}
}
and then in my master_template view I loop it as long as it has plugins in the array.
...
<?php
if(isset($js)){
foreach ($js as $item) {
echo "<script type='text/javascript' src='".base_url()."assets/".$item."'></script>";
}
}
?>
</body>
</html>
Thank you guys for the insights.