in CodeIgniter, Coding, PHP

Dynamically Add Javascript and CSS Files in CodeIgniter Header Page


Those who are developing web projects know that, header pages are always the constant file of their template folder. The classic way of using a header page in small projects are to fill it with constant JavaScript and CSS files along with html tags and use it in inside functions where you need. The problem arise when you start to develop a bigger project where you need to use different JavaScript and CSS files. The bad practice is to load all needed files in the header page, that will also start to appear and load in the pages and sections which we do not need them. This will make the page load slow and will cause conflicts and usage problems.

The solution to this problem is to dynamically load the CSS and JavaScript files in the pages we need them and make our page load faster by reducing the included files according to our exact need.

To implement this in CodeIgniter, firstly set the default CSS and JavaScript files in config.php

Default CSS and JavaScript headersPHP

$config['header_css'] = array('style.css','prettyPhoto.css','nivo-slider.css');
$config['header_js']  = array('core.js','core.js',
                              'jquery-1.4.1.min.js',
                              'jquery-slidedeck.pack.lite.js',
                              'jquery-prettyPhoto.js',
                              'jquery.nivo.slider.js');

then, add this helper functions I wrote, to your template helper (or any other helper files you use)