I’ve extended the html helper by modifying link_tag() function the to help me generate links to scripts. Needless to say, the usage is pretty much the same of link_tag().
The only default parameter is type, which is text/javascript.
Example:
echo script_tag('scripts/tiny_mce.js');
// gives <script src="http://site.com/scripts/tiny_mce.js" type="text/javascript" />
Array example:
$script = array(
'src' => 'scripts/tiny_mce.js',
'charset' => 'utf-8',
'type' => 'text/javascript',
'defer' => 'defer'
);
echo script_tag($script);
// <script src="http://site.com/scripts/tiny_mce.js" charset="utf-8" type="text/ecmascript" defer="defer" />
The function:
// ------------------------------------------------------------------------
/**
* Link
*
* Generates link to a Script file
*
* @access public
* @param mixed scripts srcs or an array
* @param string src
* @param string type
* @param string charset
* @param string defer
* @param boolean should index_page be added to the script path path
* @return string
*/
if (! function_exists('script_tag'))
{
function script_tag($src = '', $type = 'text/javascript', $charset = '', $defer = '', $index_page = FALSE)
{
$CI =& get_instance();
$script = '$v)
{
if ($k == 'src' AND strpos($k, '://') === FALSE)
{
if ($index_page === TRUE)
{
$script .= ' src="'.$CI->config->site_url($v).'" ';
}
else
{
$script .= ' src="'.$CI->config->slash_item('base_url').$v.'" ';
}
}
else
{
$script .= "$k=\"$v\" ";
}
}
$script .= "/>\n";
}
else
{
if ( strpos($src, '://') !== FALSE)
{
$script .= ' src="'.$src.'" ';
}
elseif ($index_page === TRUE)
{
$script .= ' src="'.$CI->config->site_url($src).'" ';
}
else
{
$script .= ' src="'.$CI->config->slash_item('base_url').$src.'" ';
}
$script .= ' type="'.$type.'" ';
if ($defer != '')
{
$script .= 'defer="'.$defer.'" ';
}
if ($charset != '')
{
$script .= 'charset="'.$charset.'" ';
}
$script .= '/>'."\n";
}
return $script;
}
}
