Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 2 $this->Html->script order

I am trying to insert JS files into the view but they are being inserted in the wrong order.

In my default.ctp I have this

$this->Html->script(array(
    'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js',
    'global'
), array('inline'=>false));

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

In my view I have this:

$this->Html->script('jquery.fancybox.pack', array('inline' => false));

But when I view the source it comes out like this:

<script type="text/javascript" src="/js/jquery.fancybox.pack.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="/js/global.js">

Which is obviously the wrong order so the jQuery plugin is not working.

What am I doing wrong?

like image 573
472084 Avatar asked Mar 28 '12 09:03

472084


1 Answers

Generally, I echo out the required scripts in the layout (instead of adding them to the buffer) and then script block (buffered scripts) after. This ensures that scripts required for each view are echoed first. Your default.ctp would look something like this instead:

// get echoed immediately
echo $this->Html->script(array(
    'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js',
    'global'
));
// everything else from the view, echoed after
echo $this->fetch('script');

Or, you can specify a special block for your preceding scripts.

echo $this->Html->script(array(
    'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js',
    'global'
), array('block' => 'firstScripts');
echo $this->fetch('css');
echo $this->fetch('firstScripts');
echo $this->fetch('script');
like image 125
jeremyharris Avatar answered Sep 30 '22 01:09

jeremyharris