It is better to load your .js in your footer as your HTML should fully load before your start running script over it.
see here for reasons
i use a universal footer to handle the .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 is
<?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
//look for JS for the class/controller
$class_js = "public/js/custom-".$caller_class.".js";
if(file_exists(getcwd()."/".$class_js)){
?><script type="text/javascript" src="<?php echo base_url().$class_js; ?>"></script>
<?php
}
//look for JS for the class/controller/method
$class_method_js = "public/js/custom-".$caller_class."-".$caller_method.".js";
if(file_exists(getcwd()."/".$class_method_js)){
?><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 detect what controller or method in the controller is being used. then detecting if a .js file exists for that controller/method
with little management you can have controller and/or method specific scripts without fiddling with the footer.
in file pub/js/custom-mycontrollername-mymethod.js you would then use (jquery);
$(document).ready(function() {
if ( $( "#mydivthing" ).length ) {
$('#mydivthing').html("fetching..");
$.ajax({
........
});
} else {
console.log("skipped js segment");
}
});
here the jquery only runs 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. so you are not firing events when they are not loaded (for speed). but as jquery is likely doing some checking - this is probably only helpful for larger runs of code than just single button clicks events.
while the question was for views, this answers gets to a controller/methods level. so while a method can have multiple views - this still a view/screen as seen by the user.
added bonus that you can associate .js files to controller/methods just by its filename.