Search code examples
jquerycakephpcakephp-2.x

How to defer inline jQuery in CakePHP 2.x


I load jQuery and other javascripts last in layout because of page speed optimization.

Now I have to make a jQuery script block in the view (mixing with php) but the jQuery functions obviously won't be recognised because it is loaded before jQuery is loaded.

I tried:

$this->Html->scriptStart(array('inline' => false));

but it doesn't even load it in the source code.

For debugging I tried:

$this->Html->scriptStart(array('inline' => true));

It does load but as it says, inline. No good for my needs.

How can I "defer" inline javascript and load it last, after all the other scripts and whole layout has been loaded?

One option would be to make it all with javascript but I'm going to use PHP there as well, that's why it's in the view.


Solution

  • Don't forget to include in your layout:

    <? echo $this->fetch('script');?>
    

    In your view, the following should now work:

    <? $this->Html->scriptStart(array('inline' => false)) ?>
        //Js goes here
    <? $this->Html->scriptEnd() ?>