codeigniter load view specific javascript

20,716

Solution 1

You can send which js to load as a variable. Example is here;

Sample controller

class mypage extends CI_Controller{
    public function index(){
    $data['js_to_load']="index.js";
    $this->load->view('header',$data);
    $this->load->view('my_html_page');
    }

    public function second_page(){
    $data['js_to_load']='second.js';
    $this->load->view('header',$data);
    $this->load->view('my_second_html_page');

    }
}

header.php - View file

<!-- Needed html code here -->

<? if ($js_to_load != '') : ?>

<script type="text/javascript" src="assets/js/<?=$js_to_load;?>">

<? endif;?>

<!-- Other html code here -->

Whats happening?

We are setting the js file into $data variable, and passing the $data variable to header. In header file we are checking if js_to_load is set? If yes, we are including the js file.

Also you can pass multi js files by using arrays.

Sample controller

class mypage extends CI_Controller{
    public function index(){
    $data['js_to_load']=array("index.js","index1.js","index2.js");
    $this->load->view('header',$data);
    $this->load->view('my_html_page');
    }

    public function second_page(){
    $data['js_to_load']=array("second.js","second2.js","second2.js");
    $this->load->view('header',$data);
    $this->load->view('my_second_html_page');

    }
}

header.php - View file

<!-- Needed html code here -->

<? if (is_array($js_to_load)) : ?>
<? foreach ($js_to_load as $row):
    <script type="text/javascript" src="assets/js/<?=$row;?>">
<?endforeach;?>
<? endif;?>

<!-- Other html code here -->

Solution 2

you can use a variable as a controller name and pass this variable to your view like this

Here is Controller

class Blog extends CI_Controller{
  public function index(){
    $data['controller']="blog_index";
    $this->load->view('header',$data);
  }

  public function second_page(){
   $data['controller']="blog_second_page";
   $this->load->view('header',$data);

 } 
}

Header.php File

<? if (isset($controller) && in_array($controller,array('blog_index'))) : ?>

<script type="text/javascript" src="assets/js/custom_blog_index.js">

<? endif;?>

<? if (isset($controller) && in_array($controller,array('blog_second_page'))) : ?>

  <script type="text/javascript" src="assets/js/custom_blog_second_page.js">

<? endif;?>

<!-- Other html code here -->

hope this will answer your question

Solution 3

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.

Solution 4

Pass an array of js you want added to the header in the data, and add in in the view, there are probably other ways of doing it (this kind smears the controller/view line, so it's a bit dirty, but it works).

public function index(){
    $data['title'] = "Register";     
    $data['js'] = array('link', 'link', etc);   
    $this->load->view("site_header", $data); 
    $this->load->view("site_nav"); 
    $this->load->view("content_register"); 
    $this->load->view("site_footer");
} 
Share:
20,716

Related videos on Youtube

Faiyet
Author by

Faiyet

Updated on July 09, 2022

Comments

  • Faiyet
    Faiyet almost 2 years

    I have a register view file on which there is a very big form. Hence I plan to use a form wizard plugin along with the jquery form validation plugin. I only want these scripts loaded on specific pages. How do I do this ? Here is my controller method.

    public function index(){
        $data['title'] = "Register";        
        $this->load->view("site_header", $data); 
        $this->load->view("site_nav"); 
        $this->load->view("content_register"); 
        $this->load->view("site_footer");
    } 
    

    I saw a similar post on stackoverflow here but I don't understand what to do. Please help.

    • Hashem Qolami
      Hashem Qolami almost 11 years
      This gist may be helpful. By using this, you can embed external JavaScript files and also add internal JavaScript statements into custom views.
  • Faiyet
    Faiyet almost 11 years
    that would meen having several different header files. Your suggestion is logical, however, that is too much micro management for such a simple thing. Thanks for the assist thought.
  • chromaloop
    chromaloop almost 10 years
    I used isset(); to check if $js_to_load is defined in a given controller method, otherwise I got an error. <? if (isset($js_to_load)) : ?> <script type="text/javascript" src="assets/js/<?=$js_to_load;?>"> <? endif;?>
  • Nico
    Nico over 4 years
    Note that it's a best practice to put scripts at the bottom of the page => Quote : "The problem caused by scripts is that they block parallel downloads. [...] While a script is downloading, however, the browser won't start any other downloads, even on different hostnames."