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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With