CodeIgniter: How do I include a .js file in view?

There is a lesser-known solution that works really well with clean syntax and much more portability than hard-coding URL's or relative files.

<base href="<?=base_url();?>">

<img src="images/logo.gif" alt="Logo" />

Read more about how, what, why on my article "Asset handling in CodeIgniter with the BASE tag".


First question:

It depends if you use absolute or relative urls.

Absolute urls go from the root of your domain. Relative urls are loaded relative from the current directory (including the url segments).

Second question: It's best to use an absolute URL. Because of the pretty urls, it's not recommended to use relative urls.

The easiest way is to use the url helper and then use the site url function like this:

$this->load->helper('url');
echo site_url('system/application/libraries/jquery.js');

Ps. I recommend to put things like javascript and images outside of the CodeIgniter directory.


It's not the "index.php" file that is the view. The view is whatever is loaded in your controller when you do a

$this->load->view("viewname");

The file "viewname.php" can then include the .js files, just as a normal .html (or .php) file would:

<script  src="/url/to/javascript.js" />

You may want to create a default view or a "header" view that includes some or all of the (common) .js files for your project.

-CF