Loading javascript in Code Igniter
For our Code Igniter application we are loading all of our javascript just before the closing body tag.
so in our controllers we have
$this->load->view('head', $this->head);
$this->load->view('main_view_for_controller', $data);
$this->load->view('foot', $this->foot);
And in the foot view we have a bunch of <script src="master.js"></script>
tags.
These include
- jQuery
- jQuery-ui
- shared-functions
Now this works great, until you think about JS used only on specific pages, or inline js.
You can't just dump your javascript anywhere in the page as it will generally use bit's and pieces of the parts you load at the bottom.So what I do at the moment is,
I have/application/views/js/
where I will have something like login.php
login.php
may contain e.g.
<script>
$(function(){
var user_id = <?php echo $this->user-开发者_如何学编程>get('id'); ?>;
var return = '<?php echo $return_url; ?>';
$('#login form').submit(function(){[...]});
$('#login .facebook').click(function(){[...]});
});
</script>
so in my controller I would call
$this->foot['js'][] = javascript('login', array('return_url' => '/users'));
//source of function javascript() from inside a helper
function javascript($file, $config = array()){
return $this->load->view('js/'.$file, $config, true);
}
then in my foot view after all the other files (which on the prod env are merged into one file and then minified) I have
foreach($js as $jsOut) echo $jsOut;
which simply spits out all the javascript.
Is this the best way of doing this? or is there a better way? This just seems kind of messy...
A good idea might be to use page segments to determine what scripts to include. Rather than having to populate an array all of the time, you could define your scripts and what pages they belong too, then just check the page segments to determine what JS scripts to include. Read the documentation for the URI class here.
So in your include you'd do something like this.
<?php if ( $this->$this->uri->rsegment(2) == 'login' ): ?>
// Your login page specific scripts here
<?php endif; ?>
<?php if ( $this->$this->uri->rsegment(2) == 'home' ): ?>
// Your homepage specific scripts here
<?php endif; ?>
Replace the number 2's with whatever segment relates to the page you're on.
精彩评论