CodeIgniter Forums
Where do I put my javascript code? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12)
+--- Thread: Where do I put my javascript code? (/showthread.php?tid=67019)



Where do I put my javascript code? - meSmashsta - 01-02-2017

Should I put it inside my view?

Code:
<p>Stuff...</p>
<script type="text/javascript">
alert("welcome");
</script>


Or should I use controller to load my javascript inside the view?

PHP Code:
$data = array(
 
base_url("assets/js/hello_world.js")
);
$this->load->view("index"$data); 



Then inside my view:
PHP Code:
<head>
<?
php
if (isset($js)) :
 foreach (
$js as $jv) :
 
 echo "<script src='" $jv "'></script>";
 endforeach;
endif;
?>
</head> 



RE: Where do I put my javascript code? - InsiteFX - 01-03-2017

All JavaScript code should go at the bottom of your html just above the closing body tag.

If it is needed in the html at start then it needs to go in the head section of your html.


RE: Where do I put my javascript code? - Kaosweaver - 01-03-2017

For JS management, we use the controller to setup an array of JS files (specific for the page) and then the PHP code in the view to load up the JS. We use two arrays, one for the top of the HTML (head_js_load) and one for the bottom of the HTML (footer_js_load) to keep all of the JS on the bottom of the page if we can.

We also configure the asset folders in the config.php file (config folder) so we're not typing in assets/js (or assets/css, etc - all files have standard locations). We do have an override function when prepping the array just in case a particular JS or CSS needs to be loaded from a different location.


RE: Where do I put my javascript code? - meSmashsta - 01-03-2017

So to summarize, js should be put inside the view? Ok guys, thanks!