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?
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With