Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategy for moving javascript to the bottom in CodeIgniter?

On my site I have one global Javascript file which includes jQuery and code for the drop down menu among other things. Many pages also have custom Javascript for minor page-specific interactions, tables etc.

My current set up on each view is a header.php file, basically covering everything from the doctype through to start of the content, the view file for the specific page, and a footer.php closing out the page.

Currently global.js is linked from the <head>. For performance we should put JS at the very bottom of the page, but I can't figure out a good way to do this. I could add the full script line for global.js with the custom script block, but that means I must add it on every page, even when there is no other Javascript. Any better way to move the JS right to the bottom?

like image 468
DisgruntledGoat Avatar asked Oct 07 '22 01:10

DisgruntledGoat


1 Answers

You could put the custom JS in a regular variable or nowdoc (php 5.3.0+), and then echo the variable along with script tags in the footer if it exists. Nowdoc might be preferable because you can use both double quotes and single quotes in your JS and PHP won't parse/escape the text.

someview.php:

<?php 
$custom_js = "
alert('custom js ran');
";
?>

<?php 
$custom_js = <<<'CUSTOM_JS'
alert("custom js ran (i'm in a nowdoc!)");
CUSTOM_JS;
?>

footer.php:

<?php if(isset($custom_js)) { ?>
    <script><?php echo $custom_js; ?></script>
<?php } ?>

Edit 2: If you don't want to have the javascript in a string, you could have the javascript in a seperate file and then use PHP's file_get_contents() to load it into the $custom_js variable as a string.

Edit: This is just an aside, but you might look into using the Carabiner library for loading JS and CSS. It's an excellent library. It might not necessarily help with your current problem, but if your global.js is quite large, you could split it up and use Carabiner to compress/concatenate on load. I currently use it to select which JS and CSS gets loaded for logged in and logged out users on my current CI project.

  • Carabiner on Github
  • Carabiner on Sparks
  • Carabiner documentation
like image 70
Brendan Avatar answered Oct 13 '22 09:10

Brendan