Loading javascript in Code Igniter

筅森魡賤 提交于 2021-02-08 02:08:33

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/7156323/loading-javascript-in-code-igniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!