Please wait for 15 seconds...

Tuesday, 12 February 2013



Today I will discuss with you about simple script tag function for Codeigniter. I searched on the web for this type of function but found only few complicated functions then I decided to write something simple. I am trying to put here everything simple so you can modify script_tag() according to your project need. So without wasting more time let's get started.

First of all insert below codes in your main controller or in index.php on root directory.

Try to put script_tag() at the top of the page.



MY_Controller.php


<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/***** Script Tag Function Starts *********/
if(!function_exists('script_tag')){
    function script_tag($src, $type="text/javascript", $lang="javascript"){
        return '<script type="'.$type.'" language="'.$lang.'" src="'.$src.'"></script>';
    }
}
/******** Script Tag Function Ends ***********/
class MY_Controller extends CI_Controller{
    public function __construct(){
        parent::__construct();
    }
}

OR

Index.php


/***** Script Tag Function Starts *********/
if(!function_exists('script_tag')){
    function script_tag($src, $type="text/javascript", $lang="javascript"){
        return '<script type="'.$type.'" language="'.$lang.'" src="'.$src.'"></script>';
    }
}
/******** Script Tag Function Ends ***********/

How to use it in view


script_tag() has been created let's check if it is working properly.

Copy and paste below example in your view(template) file weather it is .tpl, .html or .php it does not matter.

<?=script_tag(base_url("http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"))?>
<?=script_tag(base_url("js/functions.js"))?>

Now create a file called functions.js in js directory and insert below code in it.

$(document).ready(function(){
alert('Script file has successfully attached');
});

Now load the controller and see everything is working fine.

I hope you enjoyed the tutorial. Please leave your feedback below.

Posted by Atul Prasad Gupta

0 comments:

Post a Comment

Subscribe Techsirius

Techsirius on Facebook