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


Question

Where and how do I include .js files in Views in CodeIgniter?

I have tried this:

<script type="text/javascript" src="system/application/libraries/jquery.js"></script>

As I figured that the index.php is the one that is loading the views, so I'm guessing that every time a page is loaded the current dir path is at root because index.php is located at root. Is this true?

The above line doesn't so I am doing something wrong. I have a CodeIgniter project. The path is like this:

localhost/CodeIgniter/system/application

so which path should I use to include my jquery.js file which is located in

localhost/CodeIgniter/system/application/libraries

when I want to load the jquery.js file in a View located here:

localhost/codeIgniter/system/application/views/till_view.php
1
7
10/10/2009 5:23:48 PM

Accepted Answer

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

6
12/15/2012 3:36:16 AM

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".


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon