• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add code to controller to load a javascript file in the header?

#1
[eluser]markanderson993[/eluser]
Hello there CodeIgniter experts. I have a relatively simple question.

Is there a simple bit of code that would allow me to for instance, ask the method in the controller (just for that page) to load a javascript file in the header? An example of what I mean would be something like this:

Code:
$this->load->headerfile("js/javascript-file.js");

Is this possible?

Thanks for your help!
- Pianoman993

#2
[eluser]Jondolar[/eluser]
$this->load->view('js/javascript-file.js');

basically, load your header, then alternatively, load your jscript, then load your body template. If you need more control in where the file is inserted to put view logic in your view template and then set a variable in the data array that is passed to the view:

<? if ($js = TRUE) { ?>
javascript code
<? } ?>

#3
[eluser]slowgary[/eluser]
Jondolar,

Wouldn't that cause CodeIgniter to look for a PHP file called "javascript-file.js.php"? It would also require your javascript file to be in your views folder (/views/js/ to be exact).

I would either just include the script directly in your view, or if it needs to be loaded dynamically (only in certain cases), just pass it in as a parameter to your view.

Code:
//controller
$data['js_include'] = "< script type='text/javascript' src='myscript.js' >< /script >";



//view
<doctype>
&lt;html&gt;
&lt;head&gt;
   &lt;title&gt;My page&lt;/title&gt;
   &lt;?php if(isset($js_include)) echo $js_include; ?&gt;
&lt;/head&gt;
&lt;body&gt;
   <h1>Welcome to Pianoman's Ballerina Fansite!</h1>
&lt;/body&gt;
&lt;/html&gt;

#4
[eluser]Jondolar[/eluser]
Hi slowgary,

I was thinking that the javascript-file.js.php would have the html code:
&lt; script type='text/javascript' src='myscript.js' &gt;&lt; /script >

Your second way is what I was trying to explain but you did a better job.

#5
[eluser]markanderson993[/eluser]
Thank you for all your responses. I'll try and create some sort of if(isset) ... system to display appropriate .js files Smile


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.