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
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
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
base_url() (beside of course put the absolute url that I want to avoid).
Now my scripts.js file has access to the
base_url() value via its own
Here's my recipe for Javscript (and CSS) goodness with CI:
Grab a copy of Minify - if you don't know it already, your life will be better. Not in a "Love at first sight / I just discovered jQuery / xkcd / unit testing" kind of way, but at least in a "Dude, prepared statements eradicate SQL injection" kind of way.
Second, create a CI controller that encapsulates Minify (shouldn't be too hard, just remember to set the correct HTTP header and pass the parameters on)
Optionally activate caching to make everything run blazingly fast (Minify has caching built in, but if you're already caching your CI content, you might as well use the same method here.
Optionally define some groups for Minify, to make script loading even nicer
And presto, you should now be able to load your scripts by calling the Minify-wrapper:
It's crazy fast, it's gzipped, takes just one request rather than many, it gives you full CI control over your scripts, and it even makes your source code cleaner.
Oh, and if you want to be extra nice to your source-code-peeping visitors, you could automatically add something like this to the output:
At least that's what I do.