Last active
December 19, 2015 17:49
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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