Load Javascript files in CakePHP Layout at "bottom"
Asked Answered
L

2

11

Currently, I have a big CakePHP application with a layout and a lot of views. In the layout, I load Javascript files in the head which are needed by most views. In the views themself, I either load additional Javascript files (e.g., load a library file that is only needed there), or I add some Javascript code that is only relevant for this view in a script tag, for example if I need a click handler.

Since it is a known fact that loading Javascript files in the HTML head blocks loading the page, I wanted to put them at the bottom before closing the body Tag. But if I do so, the Javascript in my views that load the content breaks because it does not know about my loaded Javascript files. I understand that the Javascript code in the loaded views is executed before my files are loaded. But how can I prevent that?

I'm currently using the HTML Helper in the Layout (and everywhere else) to load my JS files like this:

<?php echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'); ?>

And I use the JS Helper to "output" JS at the end of the page with

<?php echo $this->Js->writeBuffer(); ?>

Is there a way I can append my JS code in the views, so that it is executed when I call writeBuffer? Can that help me out?

Landlordism answered 29/12, 2012 at 17:24 Comment(0)
D
13

This is what I do in my view:

echo $this->Html->script('filename', array('inline' => false));

And this is what I do at the bottom of my layout:

echo $this->fetch('script');
Doradorado answered 29/12, 2012 at 19:0 Comment(1)
I think this is a good solution and I think it works, if I put all my inline code in the views in Javascript files. Thanks for your advice!Landlordism
M
20

Since CakePHP version 2.1 you can use script blocks:

// in your view
$this->Html->script('filename', array('block' => 'scriptBottom'));

// in your layout
echo $this->fetch('scriptBottom');

This approach lets you keep echo $this->fetch('script') in the <head> of your layout in case you need any scripts at the top.

Malamut answered 1/1, 2013 at 0:9 Comment(2)
Thanks for your answer. In fact, I already found your answer somewhere in the web and integrated it, but it's sure worth to be mentioned here since it completes the answer.Landlordism
Do you mean is it better to not load any js in the layout <head>, just fetch them at the end of the layour and call the js you need in each view?Selenography
D
13

This is what I do in my view:

echo $this->Html->script('filename', array('inline' => false));

And this is what I do at the bottom of my layout:

echo $this->fetch('script');
Doradorado answered 29/12, 2012 at 19:0 Comment(1)
I think this is a good solution and I think it works, if I put all my inline code in the views in Javascript files. Thanks for your advice!Landlordism

© 2022 - 2024 — McMap. All rights reserved.