Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery in CodeIgniter, inside the view or in external js file?

I'm developing web application using CodeIgniter. All this time, I put the custom js code to do fancy stuffs inside the view file. By doing this, I can use site_url() and base_url() function provided by CodeIgniter.

Today I want to separate all custom js code from view file into an external js file. Then it hit me, I cannot use site_url() and base_url() in the external js file. So, I had to move the js code back into view file.

I want to ask opinion, example, and best practice for this kind of problems. Do you put the custom js code inside the view, or in external js file? If you put it in external file, how do you get around the needs for site_url() and base_url() (beside of course put the absolute url that I want to avoid).

like image 549
Donny Kurnia Avatar asked Feb 25 '10 04:02

Donny Kurnia


1 Answers

I typically keep mine in an external file, but place a single line within my template (view) that declares a javascript variable called "baseurl" that can later be used by my external javascript.

<script type="text/javascript">
  var baseurl = "<?php print base_url(); ?>";
</script>
<script type="text/javascript" src="/js/scripts.js"></script>

Now my scripts.js file has access to the base_url() value via its own baseurl variable.

like image 111
Sampson Avatar answered Oct 19 '22 11:10

Sampson