Skip to content

Instantly share code, notes, and snippets.

@theshem
Last active December 19, 2015 17:49
Show Gist options
  • Save theshem/5994689 to your computer and use it in GitHub Desktop.
Save theshem/5994689 to your computer and use it in GitHub Desktop.
CodeIgniter Snippet: How to load JavaScript files and/or code on a specific view
<?php
class Sample_controller extends CI_Controller {
/**
* Foo()
* @return void
*/
public function foo()
{
// External JavaScript files
$data['js'] = array(
'/path/to/your/js_file_1.js',
'/path/to/your/js_file_2.js',
'/path/to/your/js_file_3.js'/* ,
and so on... */
);
// Internal JavaScript Code
$data['js'][] = "$(document).ready(function($) {
$('body').removeClass('loader');
});";
$this->load->view('sample_view', $data);
}
}
<?php
if (! empty($js) && is_array($js)) {
/**
* To store internal JavaScript code
*/
$_js_scripts = array();
// Perform a loop on $js array and attach external js files
foreach ($js as $script) {
// Check whether or not $script is an external javascript URL
if (preg_match("/.+\.js$/m", $script)) {
echo "<script type=\"text/javascript\" src=\"$script\"></script>".PHP_EOL;
} else {
// Store Javascript internal code
$_js_scripts[] = $script;
}
}
// Write Internal JavaScript statements right after embeding external ones
if (! empty($_js_scripts)) {
echo '<script type="text/javascript">'.PHP_EOL. implode(PHP_EOL, $_js_scripts) .PHP_EOL.'</script>'.PHP_EOL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment