Itβs better to load your .js in the footer , since your HTML should be fully loaded before your script runs on top of it.
see here for reasons
I am using a universal footer to process .js files.
public function index() { $this->load->view('template/header'); $this->load->view('template/nav'); $this->load->view('thing/landing'); $this->load->view('template/footer'); }
my footer view
<?php defined('BASEPATH') OR exit('No direct script access allowed'); $caller_class = $this->router->class; $caller_method = $this->router->fetch_method(); ?> <script type="text/javascript" src="<?php echo base_url(); ?>public/js/jquery.min.js"></script> <?php <script type="text/javascript" src="<?php echo base_url().$class_js; ?>"></script> <?php } <script type="text/javascript" src="<?php echo base_url().$class_method_js; ?>"></script> <?php } ?> </body> </html>
using $this->router->class; or $this->router->fetch_method(); to determine which controller or method is used in the controller. then detects if a .js file exists for this controller / method
with little control, you may have scripts with a controller and / or a specific method without using a footer.
in the pub / js / custom-mycontrollername-mymethod.js file that you would use (jquery);
$(document).ready(function() { if ( $( "#mydivthing" ).length ) { $('#mydivthing').html("fetching.."); $.ajax({ ........ }); } else { console.log("skipped js segment"); } });
here jquery only starts when the document is ready (as jquery recommends) and you can also use if ( $( "#mydivthing" ).length ) { to check that your div is actually on the page. therefore, you do not fire events when they are not loading (for speed). but since jquery most likely does some validation - this is probably only useful for large runs of code than for events with a single click.
while the question was for views, these answers fall at the controller / method level. therefore, although the method can have several views, it is still a view / screen, as seen by the user.
Added a bonus that can be associated with .js files with the controller / methods only by the file name.
source share